[英]How to avoid infinite loop in BFS?
這是 LeetCode 問題 542。01矩陣
我的代碼將創建一個無限循環,因為它會將每個方向推入隊列,即使該節點已被訪問。 我想不出解決這個問題的方法。 有人可以幫忙嗎?
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;
}
}
您必須跟蹤已經訪問過的節點。 您可以將節點保留在列表中,也可以將它們移動到單獨的Set
。
您在這里遇到的問題是節點是數組,您不能在HashSet
使用它們。 我首先聲明一個類Coordinates
:
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:使用單獨的Set
既然我們有了hashCode
和equals
方法,為什么不使用HashSet
呢?
不過,我將把它作為練習。
將節點地址封裝在一個可以實現 hashcode 和 equals 的類中,如本答案中所建議的。 節點類可以很簡單:
class Node {
private final int[] address;
Node(int[] address){
this.address = address;
}
@Override
public boolean equals(Object other) {
if(other == null ||!(other instanceof Node)) return false;
return Arrays.equals(address, ((Node)other).getAddress());
}
@Override
public int hashCode() {
return Arrays.hashCode(address);
}
public int[] getAddress() {
return address;
}
}
它允許您維護訪問節點的集合: Set<Node> visited = new HashSet<>();
當visited.add(node)
返回false時,就知道visited
已經包含node
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.