JZ13 机器人的运动范围
描述
地上有一个 rows 行和 cols 列的方格。坐标从 [0,0] 到 [rows-1,cols-1] 。一个机器人从坐标 [0,0] 的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于 threshold 的格子。 例如,当 threshold 为 18 时,机器人能够进入方格 [35,37] ,因为 3+5+3+7 = 18。但是,它不能进入方格 [35,38] ,因为 3+5+3+8 = 19 。请问该机器人能够达到多少个格子?
代码
public class Solution {
int result = 0;
public int movingCount(int threshold, int rows, int cols) {
boolean[][] flag = new boolean[rows][cols];
countMove(threshold, rows, cols, 0, 0, flag);
return result;
}
public void countMove(int threshold, int rows, int cols, int r, int c, boolean[][] flag) {
if (r < 0 || r >= rows || c < 0 || c >= cols || flag[r][c] || (r / 10 + r % 10 + c / 10 + c % 10) > threshold) {
return;
}
flag[r][c] = true;
result++;
countMove(threshold, rows, cols, r + 1, c, flag);
countMove(threshold, rows, cols, r, c + 1, flag);
}
}
题目解析
整体思路;
不能用遍历,因为某些点不可达,考虑递归,(0,0)点为起始点,向下和向右探测是否满足条件。
知识点:
- 十位和个位的数字之和 : r / 10 + r % 10
- 标记已经探测的点 :
boolean[][] flag = new boolean[rows][cols]
- 递归的使用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?