class Solution {
public int movingCount(int m, int n, int k) {
int res = 1;
// 向右上方移动
int[][] move = new int[][] {{1, 0}, {0, 1}};
// 记录某个位置是否访问过
boolean[][] visit = new boolean[m][n];
// 维护可到达的点队列
Queue<Point> queue = new LinkedList<>();
queue.offer(new Point(0, 0));
visit[0][0] = true;
while (!queue.isEmpty()) {
Point currPoint = queue.poll();
for (int i = 0; i < move.length; i++) {
int nextX = currPoint.x + move[i][0];
int nextY = currPoint.y + move[i][1];
if (check(nextX, nextY, m, n, k, visit)) {
queue.offer(new Point(nextX, nextY));
visit[nextX][nextY] = true;
res++;
}
}
}
return res;
}
// 判断某个位置是否合法
private boolean check(int x, int y, int m, int n, int k, boolean[][] visit) {
if (x >= 0 && x < m && y >= 0 && y < n && !visit[x][y] && getNumericalDigit(x) + getNumericalDigit(y) <= k) {
return true;
}
return false;
}
// 获取一个整数的数位和
private int getNumericalDigit(int num) {
int res = 0;
while (num > 0) {
res += num % 10;
num /= 10;
}
return res;
}
}
// 坐标对象类
class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
机器人的运动范围java(广搜)
最新推荐文章于 2024-03-22 20:51:14 发布