机器人的运动范围
机器人的运动范围
地上有一个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 count=0;
int[]visited;
int k;
int rows,cols;
//这里直接标定哪些是不能访问的,可以省去每次到了都计算一遍的麻烦,所以visited数组也不能用布尔值了
//将0作为NOT_VISITED,省的初始化
//这样做也减少了magic number,符合规范
private static int UNACCESSABLE=-1,VISITED=1,NOT_VISITED=0;
public int movingCount(int threshold, int rows, int cols)
{
visited=new int[rows*cols];
k=threshold;
this.rows=rows;
this.cols=cols;
test(0,0);
return count;
}
private void test(int i,int j){
if(visited[i*cols+j]!=NOT_VISITED){
return;
}
int testSum=0,tempI=i,tempJ=j;
while(tempI>0){
testSum+=tempI%10;
tempI=tempI/10;
}
while(tempJ>0){
testSum+=tempJ%10;
tempJ=tempJ/10;
}
if(testSum>k){
visited[i*cols+j]=UNACCESSABLE;
return;
}else{
count++;
visited[i*cols+j]=VISITED;
}
if(i>0){
test(i-1,j);
}
//注意这里千万不能写else if,因为我们是希望它都执行的
if(i<rows-1){
test(i+1,j);
}
if(j>0){
test(i,j-1);
}
if(j<cols-1){
test(i,j+1);
}
return;
}
}