机器人的运动范围
这题目虽然代码有点长,但是思路非常清晰,所以不难
class Solution {
public int movingCount(int threshold, int rows, int cols) {
if (rows == 0 || cols == 0)
return 0;
Queue<pair> queue = new LinkedList<>();
queue.offer(new pair(0, 0));
int res = 0, x = 0, y = 0;
int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
boolean[][] st = new boolean[rows][cols];
while (!queue.isEmpty()) {
pair p = queue.poll();
if (p.getS(p.row) + p.getS(p.col) > threshold || st[p.row][p.col] == true)
continue;
res++;
st[p.row][p.col] = true;
for (int i = 0; i < 4; i++) {
int a = p.row + dx[i], b = p.col + dy[i];
if (a >= 0 && a < rows && b >= 0 && b < cols)
queue.offer(new pair(a, b));
}
}
return res;
}
class pair{
int row;
int col;
pair(int x,int y){
row = x;
col = y;
}
int getS(int x){
int sum = 0;
while (x > 0){
sum = sum + (x % 10);
x /= 10;
}
return sum;
}
}
}