AcWing 24. 机器人的运动范围--Java BFS 来一发
原题链接
简单
作者:
wxc
,
2019-05-27 00:38:26
,
所有人可见
,
阅读 3067
Java 代码
class Solution {
private static class Node {
int first;
int second;
public Node(int first, int second) {
this.first = first;
this.second = second;
}
}
private boolean[][] visited = new boolean[55][55];
private static final int[][] nxt = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public int movingCount(int threshold, int rows, int cols) {
if (rows < 1 || cols < 1)
return 0;
Queue<Node> que = new LinkedList<>();
visited[0][0] = true;
que.add(new Node(0, 0));
int res = 0;
while (!que.isEmpty()) {
Node popNode = que.poll();
res++;
for (int i = 0; i < nxt.length; i++) {
int fx = popNode.first + nxt[i][0], fy = popNode.second + nxt[i][1];
if (fx >= 0 && fy >= 0 && fx < rows && fy < cols && getSum(fx, fy) <= threshold && !visited[fx][fy]) {
que.add(new Node(fx, fy));
visited[fx][fy] = true;
}
}
}
return res;
}
private int getSum(int rows, int cols) {
int s = 0;
while (rows > 0) {
s += rows % 10;
rows /= 10;
}
while (cols > 0) {
s += cols % 10;
cols /= 10;
}
return s;
}
}
终于看到一个java的队列了,谢谢楼主了
想问一下,为什么private boolean[][] visited = new boolean[55][55] 这行中用的是55呀
题目中m和n的范围给定了,所以直接初始化成最大的矩阵尺寸就好