广度优先搜索
广度优先搜索BFS先用先进先出的队列存储新节点,等当前层的新节点都搜索完毕之后再搜索下一层节点。
广度优先搜索常用来处理最短路径问题。
leetcode 934
分析
广度优先搜索求最短距离。首先寻找第一个座岛,之后按层向外查找,直到找到第二座岛。
源码
class Solution {
public int shortestBridge(int[][] grid) {
Queue<int[]> queue = new ArrayDeque<>();
int n = grid.length;
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1 && queue.isEmpty()) {
dfs(grid, queue, i, j, n);
}
}
}
int step = 0;
while (!queue.isEmpty()) {
int sz = queue.size();
for (int k = 0; k < sz; k++) {
int[] cell = queue.poll();
for (int[] dir : dirs) {
int nx = cell[0] + dir[0];
int ny = cell[1] + dir[1];
if (nx >= 0 && nx < n && ny >= 0 && ny < n) {
if (grid[nx][ny] == 0) {
queue.offer(new int[]{nx, ny});
grid[nx][ny] = -1;
} else if (grid[nx][ny] == 1) {
return step;
}
}
}
}
step++;
}
return 0;
}
private void dfs(int[][] grid, Queue<int[]> queue, int curI, int curJ, int n) {
if (curI < 0 || curI >= n || curJ < 0 || curJ >= n) {
return;
}
if (grid[curI][curJ] != 1) {
return;
}
grid[curI][curJ] = -1;
queue.offer(new int[]{curI, curJ});
dfs(grid, queue, curI + 1, curJ, n);
dfs(grid, queue, curI - 1, curJ, n);
dfs(grid, queue, curI, curJ + 1, n);
dfs(grid, queue, curI, curJ - 1, n);
}
}