题目
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路
回溯法,设置一个boolean数组,记录走过的格子,避免重复,以及判断当前格子是否符合要求
代码
public class Solution {
int count = 0;
public int movingCount(int threshold, int rows, int cols)
{
boolean[][] flags = new boolean[rows][cols];//记录是否走过
deal(threshold,rows,cols,0,0,flags);
return count;
}
public void deal(int threshold,int rows, int cols, int row, int col,boolean[][] flags){
if(row>=rows || col>=cols || row<0 || col<0) return;
if(flags[row][col]==true) return;
int all= getPlus(row)+getPlus(col);
if(all>threshold) return;
count++;
flags[row][col] = true;
deal(threshold,rows,cols,row+1,col,flags);
deal(threshold,rows,cols,row-1,col,flags);
deal(threshold,rows,cols,row,col+1,flags);
deal(threshold,rows,cols,row,col-1,flags);
}
public int getPlus(int target){//统计数字和
int all = 0;
while(target!=0){
all += target%10;
target/=10;
}
return all;
}
}