题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路:
从0.0开始,进行回溯。看代码 一目了然
public class Solution {
int count =0;
public int movingCount(int threshold, int rows, int cols)
{
int [][]array=new int[rows][cols];
if(canMoving(threshold, rows, cols, 0, 0, array)){
moving(threshold, rows, cols, 0, 0,array);
count++;
}
return count;
}
public void moving(int threshold,int rows,int cols,int r,int c,int [][]array){
array[r][c]=1;
if(canMoving(threshold, rows, cols,r+1,c,array)){
count++;
moving(threshold, rows, cols, r+1, c,array);
}
if(canMoving(threshold, rows, cols,r-1,c,array)){
count++;
moving(threshold, rows, cols, r-1, c,array);
}
if(canMoving(threshold, rows, cols,r,c+1,array)){
count++;
moving(threshold, rows, cols, r, c+1,array);
}
if(canMoving(threshold, rows, cols,r,c-1,array)){
count++;
moving(threshold, rows, cols, r, c-1,array);
}
}
public boolean canMoving(int threshold,int rows,int cols,int row,int col,int[][]array){
if(row<0||col<0||row>=rows||col>=cols||array[row][col]==1)return false;
int num=0;
while(row>0){
num+=row%10;
row/=10;
}
while(col>0){
num+=col%10;
col/=10;
}
if(num<=threshold)return true;
return false;
}
}