地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
public class Solution {
int counter=0;
int rows;
int cols;
int flag[][];
public boolean sum(int k,int r,int c){
int sum = 0;
while(r>0){
sum = sum + r%10;
r = r/10;
}
while(c>0){
sum = sum + c%10;
c = c/10;
}
if(sum<=k){
return true;
}else{
return false;
}
}
public void move(int threshold, int r, int c)
{
if(r>=0&&c>=0&&r<this.rows&&c<this.cols
&&sum(threshold,r,c)
&&flag[r][c]!=1){
System.out.println(r+","+c);
counter++;
flag[r][c]=1;
move(threshold,r,c+1);
move(threshold,r+1,c);
move(threshold,r-1,c);
move(threshold,r,c-1);
}
}
public int movingCount(int threshold, int rows, int cols){
this.rows = rows;
this.cols=cols;
flag = new int[rows+1][cols+1];
move(threshold,0,0);
return counter;
}
}