题目描述:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子
思路解析:
- 方格可以看成m*n的矩阵,要判断一个是否合适,合适的话就把它附近的点也判断一下,计数;
- 注意要用Boolean数组标识已经计数的格子
- 首先判断参数的合法性,然后递归回溯。
代码:
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{ //判断参数的合法性
if(threshold<0||rows<1||cols<1){
return 0;
}
//用于标识已经计数的格子
boolean[] visited = new boolean[rows*cols];
//初始化为false
for(int i=0;i<visited.length;i++){
visited[i]=false;
}
return movingCountCore(threshold,rows,cols,0,0,visited);
}//递归回溯
private static int movingCountCore(int threshold,int rows,int cols,int row,int col,boolean[] visited){
int count =0;
if(check(threshold,rows,cols,row,col,visited)){
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;
}/**
*判断能不能进入第(row,col)的方格
*/
private static boolean check(int threshold,int rows,int cols,int row,int col,boolean[] visited){
return col>=0 && col<cols && row>=0 && row<rows && !visited[row*cols+col]
&& (getDigitSum(col)+getDigitSum(row)<=threshold);
}
/**一个数字的数位之和
*@return 数字的数位之和
*/
private static int getDigitSum(int number){
int result=0;
while(number>0){
result +=(number%10);
number/=10;
}
return result;
}
}