AcWing 24. 机器人的运动范围 -- JAVA最新手写法
原题链接
简单
JAVA 代码
class Solution {
static int steps = 0;
static int[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
static class Point{
int x,y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public static int movingCount(int threshold, int rows, int cols) {
if (rows <= 0 || cols <= 0){
return 0;
}
int[][] book = new int[rows + 1][cols + 1];
Queue<Point> queue = new LinkedList<>();
queue.add(new Point(0,0));
steps++;
book[0][0] = 1;
while (!queue.isEmpty()){
Point p = queue.poll();
if (p != null){
for (int i = 0; i < 4; i++) {
int x = p.x + dx[i];
int y = p.y + dy[i];
// 满足条件才加进队列
if (x >= 0 && x < rows && y >=0 && y< cols && reachable(x,y,threshold,book)){
queue.add(new Point(x,y));
book[x][y] = 1;
steps++;
}
}
}
}
return steps;
}
private static boolean reachable(int x, int y, int threshold, int[][] book){
if (book[x][y] == 1){
return false;
}
while (x > 0){
threshold -= x %10;
x /= 10;
}
while (y > 0){
threshold -= y%10;
y /= 10;
}
return threshold >= 0;
}
}