机器人的运动范围
地上有一个 mm 行和 nn 列的方格,横纵坐标范围分别是 0∼m−10∼m−1 和 0∼n−10∼n−1。
一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。
但是不能进入行坐标和列坐标的数位之和大于 kk 的格子。
请问该机器人能够达到多少个格子?
思路一:
宽度优先遍历,用一个队列来存储符合条件的格子,从0,0开始,由于0,0必定符合条件就入队列,队列只要不空,就将队列头部弹出,然后当前弹出的那个点的上下左右有没有符合条件的格子,如果有就入队列,直到最后符合条件且符合连续判断过程的格子全部弹出,这期间用一个res变量记录格子数量就可以。
class Solution {
class Node{
int x;
int y;
Node(int x,int y){
this.x = x;
this.y = y;
}
}
private int dec[][] = {{0,1},{0,-1},{1,0},{-1,0}};
public int movingCount(int threshold, int rows, int cols){
if(rows < 1 || cols < 1)return 0;
boolean flag[][] = new boolean[rows][cols];
Node node = new Node(0,0);
flag[0][0] = true;
Queue<Node>queue = new LinkedList<Node>();
queue.add(node);
int res = 0;
while(!queue.isEmpty()){
Node pnode = queue.poll();
res ++;
for(int i = 0;i < dec.length;i++){
int x = pnode.x + dec[i][0],y = pnode.y + dec[i][1];
if(x >= 0 && x < rows && y >= 0 && y < cols && getsum(x,y) <= threshold && !flag[x][y]){
queue.add(new Node(x,y));
flag[x][y] = true;
}
}
}
return res;
}
public int getsum(int x,int y){
int s = 0;
while(x > 0){
s += x % 10;
x /= 10;
}
while(y > 0){
s += y % 10;
y /= 10;
}
return s;
}
}
思路二:
用递归去判断每个格子,并且用boolean矩阵标记,不能走回头路;
class Solution {
public static int movingCount(int limtNumber,int row,int col){
if(row<0||col<0||limtNumber<0){
return -1;
}
boolean marked[][] = new boolean [row][col];
for(int i = 0;i < row;i++){
for(int j =0;j < col;j++){
marked[i][j] = false;
}
}
return move(0,0,limtNumber,row,col,marked);
}
private static int move(int r, int c, int limtNumber, int row, int col, boolean[][] marked) {
int count = 0;
if(checked(r,c,limtNumber,row,col,marked)){
marked[r][c] = true;
count = move(r,c-1,limtNumber,row,col,marked)+
move(r,c+1,limtNumber,row,col,marked)+
move(r-1,c,limtNumber,row,col,marked)+
move(r+1,c,limtNumber,row,col,marked)+1;
}
return count;
}
private static boolean checked(int r, int c, int limtNumber, int row, int col, boolean[][] marked) {
if(r<row&&r>=0&&c<col&&c>=0&&(sadd(r)+sadd(c))<=limtNumber&&marked[r][c]==false)
return true;
else
return false;
}
private static int sadd(int x) {
int sum = 0;
while(x>0){
sum+=x%10;
x/=10;
}
return sum;
}
}