机器人的运动范围
机器人的运动范围
http://www.nowcoder.com/questionTerminal/6e5207314b5241fb83f2329e89fdecc8
题目:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
public class Solution {
private static int sum;
public static int movingCount(int threshold, int rows, int cols)
{
sum = 0;
boolean[][] vis = new boolean[rows][cols];
solve(0,0,threshold,rows,cols,vis);
return sum;
}
private static int cal(int x, int y) {
// TODO Auto-generated method stub
int result = 0;
while(x!=0) {
result =result + x%10;
x = x/10;
}
while(y!=0) {
result =result + y%10;
y = y/10;
}
return result;
}
private static void solve(int x,int y,int threshold, int rows, int cols, boolean[][] vis) {
// TODO Auto-generated method stub
if(x<0 || x>rows-1 || y<0 || y > cols-1 ||vis[x][y] || (cal(x,y) > threshold)) {
return;
}
vis[x][y] = true;
sum ++;
solve(x+1,y,threshold,rows,cols,vis);//下
solve(x-1,y,threshold,rows,cols,vis);//上
solve(x,y+1,threshold,rows,cols,vis);//右
solve(x,y-1,threshold,rows,cols,vis);//左
}
}
查看23道真题和解析