这是LeetCode问题542. 01 Matrix
我的代码将创建一个无限循环,因为它将把每个方向插入队列,即使该节点已经被访问过。 我想不出办法来解决这个问题。有人可以帮忙吗?
class Solution {
int[][] dirs = { {0,1},{0,-1},{1,0},{-1,0} };
public int[][] updateMatrix(int[][] matrix) {
for(int i=0;i < matrix.length;i++){
for(int j=0; j < matrix[i].length;j++){
if(matrix[i][j] == 1)
matrix[i][j] = Integer.MAX_VALUE;
BFS(new int[]{i,j},matrix);
}
}
return matrix;
}
public void BFS(int[] node,int[][] matrix){
if(matrix[node[0]][node[1]] == 0)
return;
LinkedList<int[]> queue = new LinkedList<>();
queue.push(node);
int step = 1;
while(!queue.isEmpty()){
int[] temp = queue.poll();
if(temp == null){
step++;
continue;
}
for(int[] dir:dirs){
int r = temp[0] + dir[0];
int c = temp[1] + dir[1];
if(r < 0 || c < 0 || r >= matrix.length || c >= matrix[r].length)
continue;
queue.push(new int[] {r,c});
if(matrix[r][c] == 0){
matrix[temp[0]][temp[1]] = Math.min(step,matrix[temp[0]][temp[1]]);
}
}
queue.push(null);
}
return;
}
}
最佳答案
您必须跟踪已访问过的节点。您可以将节点保留在列表中,也可以将它们移动到单独的集合
。
这里的问题是节点是数组,你不能在HashSet
中使用它们。我首先声明一个类坐标
:
public class Coordinates {
public final int row;
public final int col;
public Coordinates(int r, int c) {
this.row = r;
this.col = c;
}
@Override
public int hashCode() {
return (row + 37*col) & 0x7FFFFFFF;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != getClass()) {
return false;
}
Coordinates o = (Coordinates)other;
return row == o.row && col == o.col;
}
}
选项 1:将节点保留在队列中
我不明白将null
添加到队列中的目的;我刚刚删除了这个。
public void BFS(Coordinates node,int[][] matrix){
if(matrix[node.row][node.col] == 0)
return;
List<Coordinates> queue = new ArrayList<>();
queue.add(node);
for (int i = 0; i < queue.size(); ++i) {
Coordinates temp = queue.get(i);
for(int[] dir:dirs){
int r = temp.row + dir.row;
int c = temp.col + dir.col;
if(r < 0 || c < 0 || r >= matrix.length || c >= matrix[r].length)
continue;
Coordinates newCoord = new Coordinates(r, c);
if (!queue.contains(newCoord)) {
queue.add(newCoord);
}
if(matrix[r][c] == 0){
matrix[temp.row][temp.col] = Math.min(step,matrix[temp.row][temp.col]);
}
}
}
return;
}
选项 2:使用单独的集
现在我们有了一个 hashCode
和一个 equals
方法,为什么不使用 HashSet
呢?
不过,我会将其作为练习。
关于java - 如何避免BFS中的无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54076095/