地上有一個(gè)m行和n列的方格缩抡。一個(gè)機(jī)器人從坐標(biāo)0,0的格子開始移動奠宜,每一次只能向左,右瞻想,上压真,下四個(gè)方向移動一格,但是不能進(jìn)入行坐標(biāo)和列坐標(biāo)的數(shù)位之和大于k的格子蘑险。 例如滴肿,當(dāng)k為18時(shí),機(jī)器人能夠進(jìn)入方格(35,37)佃迄,因?yàn)?+5+3+7 = 18泼差。但是,它不能進(jìn)入方格(35,38)呵俏,因?yàn)?+5+3+8 = 19堆缘。請問該機(jī)器人能夠達(dá)到多少個(gè)格子?
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;
}
}