题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
来源:https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8?tpId=13&tqId=11219&tPage=4&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
int[][] flag = new int[rows][cols];//标记是否被访问过
return movingCount(0,0,flag,threshold, rows,cols);
}
public int movingCount(int i,int j,int[][] flag,int threshold,int rows, int cols){
//判断该位置是否满足条件:1.越界? 2.是否被访问? 3.是否满足标准?
if(i<0||i>=rows||j<0||j>=cols||flag[i][j]==1||check(i)+check(j)>threshold){
return 0;
}
//满足则标记该位置已访问
flag[i][j] = 1;
//上下左右回溯
return 1+movingCount(i-1,j,flag,threshold,rows,cols)
+movingCount(i+1,j,flag,threshold,rows,cols)
+movingCount(i,j-1,flag,threshold,rows,cols)
+movingCount(i,j+1,flag,threshold,rows,cols);
}
//计算下标值
public int check(int num){
int sum = 0;
while(num>0){
sum += num%10;
num /=10;
}
return sum;
}
}