机器人的运动范围
//思路:
//flood-fill 算法
private int m;
private int n;
private boolean[][] visited;
private int[][] d={
{0,1}, //向右
{-1,0},//向上
{0,-1},//向左
{1,0} //向下
};
private boolean inArea(int x,int y){
return (x>=0 && x<m) && (y>=0 && y<n);
}
//获取一个数各个位上的数字相加
private int getNum(int num){
int sum = 0;
while(num>0){
sum += num %10;
num/=10;
}
return sum;
}
private boolean valid(int threshlod ,int x,int y){
return (getNum(x)+getNum(y))<=threshlod;
}
private int walk(int threshold,int startx,int starty){
visited[startx][starty]=true;
int walks = 1;
for(int i=0;i<4;i++){
int newX = startx+d[i][0];
int newY = starty+d[i][1];
if(inArea(newX,newY)){
if(!visited[newX][newY] && valid(threshold,newX,newY)){
walks += walk(threshold,newX,newY);
}
}
}
return walks;
}
public int movingCount(int threshold, int rows, int cols) {
if(threshold<0){ //threshold<0,则机器人就不能走了
return 0;
}
m = rows;
if(m==0){
return 0;
}
n= cols;
visited = new boolean[m][n];
return walk(threshold,0,0);
}