DFS
BFS
LeetCode
934. 最短的桥
二维数组中存在两座岛屿(1表示陆地,0表示水),现在可以将0翻转1,求使得两座岛屿连接起来需要翻转0的最小数目。
class Node {
int r;
int c;
public Node(int r, int c) {
this.r = r;
this.c = c;
}
}
private int rows;
private int cols;
//上下左右
private int[] dirR = {-1, 1, 0, 0};
private int[] dirC = {0, 0, -1, 1};
private Queue<Node> queue = new LinkedList();
public int shortestBridge(int[][] A) {
rows = A.length;
cols = A[0].length;
boolean isFindFirst = false;
//第一座岛屿染色
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (A[i][j] == 0) continue;
dfs(A, i, j);
isFindFirst = true;
break;
}
if (isFindFirst) break;
}
// bfs扩散寻找第二座岛屿
int step = 0;
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
Node node = queue.poll();
for (int i = 0; i < dirR.length; i++) {
int nextR = node.r + dirR[i], nextC = node.c + dirC[i];
if (!isInArea(nextR, nextC) || A[nextR][nextC] == 2) continue;
if (A[nextR][nextC] == 1) return step;
A[nextR][nextC] = 2;
queue.offer(new Node(nextR, nextC));
}
}
step++;
}
return step;
}
private boolean isInArea(int i, int j) {
return i >= 0 && i < rows && j >= 0 && j < cols;
}
private void dfs(int[][] graph, int r, int c) {
queue.offer(new Node(r, c));
graph[r][c] = 2;
for (int i = 0; i < dirR.length; i++) {
int nextR = r + dirR[i], nextC = c + dirC[i];
if (!isInArea(nextR, nextC) || graph[nextR][nextC] != 1) continue;
dfs(graph, nextR, nextC);
}
}
首先找到第一座岛(dfs),然后从第一座岛屿开始扩散到第二座岛屿(bfs)。