在给定的二维二进制数组 A 中,存在两座岛。(岛是由四面相连的 1 形成的一个最大组。)
现在,我们可以将 0 变为 1,以使两座岛连接起来,变成一座岛。
返回必须翻转的 0 的最小数目。(可以保证答案至少是 1 。)
示例 1:
输入:A = [[0,1],[1,0]]
输出:1
示例 2:
输入:A = [[0,1,0],[0,0,0],[0,0,1]]
输出:2
示例 3:
输入:A = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
输出:1
提示:
2 <= A.length == A[0].length <= 100
A[i][j] == 0 或 A[i][j] == 1
class Solution {
int[][] grid;
int n, m;
int[] dirs = new int[]{-1, 0, 1, 0, -1};
Deque<int[]> q = new LinkedList<>();
public int shortestBridge(int[][] grid) {
this.grid = grid;
n = grid.length; m = grid[0].length;
//dfs标记第一个块
for (int i = 0; i < n; ++i) {
boolean flag = false;
for (int j = 0; j < m; ++j)
if (grid[i][j] == 1) {
grid[i][j] = -1;
q.addLast(new int[]{i, j});
dfs(i, j);
flag = true;
break;
}
if (flag) break;
}
int res = -1;
//bfs寻找第二个块
while (!q.isEmpty()) {
int size = q.size();
res ++;
while (size -- > 0) {
int[] t = q.pollFirst();
int x = t[0], y = t[1];
for (int i = 0; i < 4; ++i) {
int a = x + dirs[i], b = y + dirs[i + 1];
if (a < 0 || a >= n || b < 0 || b >= m) continue;
if (grid[a][b] == -1) continue;
//找到第二块陆地了
if (grid[a][b] == 1) return res;
grid[a][b] = -1;
q.addLast(new int[]{a, b});
}
}
}
return res;
}
void dfs(int x, int y) {
for (int i = 0; i < 4; ++i) {
int a = x + dirs[i], b = y + dirs[i + 1];
if (a < 0 || a >= n || b < 0 || b >= m) continue;
if (grid[a][b] == 0 || grid[a][b] == -1) continue;
q.addLast(new int[]{a, b});
grid[a][b] = -1;
dfs(a, b);
}
}
}