public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
boolean flag[]=new boolean[rows*cols];
int count=movingCountCore(threshold,rows,cols,0,0,flag);
return count;
}
public int movingCountCore(int threshold, int rows, int cols,int row,int col,boolean[] flag){
int count=0;
if(check(threshold,rows,cols,row,col,flag)){
flag[row*cols+col]=true;
count=1+movingCountCore(threshold,rows,cols,row-1,col,flag)
+movingCountCore(threshold,rows,cols,row+1,col,flag)
+movingCountCore(threshold,rows,cols,row,col-1,flag)
+movingCountCore(threshold,rows,cols,row,col+1,flag);
}
return count;
}
public boolean check(int threshold,int rows,int cols,int row,int col,boolean[] flag){
if(row<rows&&row>=0&&col<cols&&col>=0&&getDig(row)+getDig(col)<=threshold&&!flag[row*cols+col]){
return true;
}
return false;
}
public int getDig(int num){
int sum=0;
while(num>0){
sum+=num%10;
num/=10;
}
return sum;
}
}
面试题67:机器人的运动范围
最新推荐文章于 2021-10-28 22:55:43 发布