1.本题知识点
回溯法,矩阵
2. 题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
3. 思路
首先,要把题目搞明白。机器人达到多个格子,也就是说求的是一个并集,上下左右四种情况都加起来就可以了,并且我们只需要考虑移动一步的情况。而上一题考虑的是一条路径(需要遍历)。
图示了一种行走轨迹,题目要求所有轨迹一共可以经过多少格子。
终止条件: 就是机器人走不动了,即上下左右都没法走了,走不动了有2种情况,一种是走到了边缘没路了,另一种是周围都已经走过了,无法重复进入!
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5e79067655680b206a62db3649e7960d.png)
Java版本:
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
int count = 0;
if(threshold < 1 || rows < 1 || cols < 1){
return count;
}
boolean [] visited = new boolean [rows * cols];
count = movingCountCore(threshold,rows,cols,0,0,visited);
return count;
}
int movingCountCore(int threshold, int rows, int cols,
int row,int col,boolean []visited){
int count = 0;
if(row < rows && col < cols && row >=0 && col >=0
&& (getDigitSum(row) + getDigitSum(col)) <= threshold
&& !visited[row * cols + col])
{
visited[row * cols + col] = true;
count = 1 + movingCountCore(threshold,rows,cols,row - 1,col,visited)
+ movingCountCore(threshold,rows,cols,row + 1,col,visited)
+ movingCountCore(threshold,rows,cols,row,col - 1,visited)
+ movingCountCore(threshold,rows,cols,row,col + 1,visited);
}
return count;
}
int getDigitSum(int number){
int sum = 0;
while(number != 0){
sum += number % 10;
number /= 10;
}
return sum;
}
}