Problem
In a given 2D binary array A, there are two islands. (An island is a 4-directionally connected group of 1s not connected to any other 1s.)
Now, we may change 0s to 1s so as to connect the two islands together to form 1 island.
Return the smallest number of 0s that must be flipped. (It is guaranteed that the answer is at least 1.)
Example 1:
Input: [[0,1],[1,0]]
Output: 1
Example 2:
Input: [[0,1,0],[0,0,0],[0,0,1]]
Output: 2
Example 3:
Input: [[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]]
Output: 1
Note:
1 <= A.length = A[0].length <= 100
Ai == 0 or Ai == 1
Solution
class Solution {
public int shortestBridge(int[][] A) {
//find the first island, using dfs
int m = A.length, n = A[0].length;
boolean[][] visited = new boolean[m][n];
Queue<int[]> queue = new LinkedList<>(); //for bfs
int[][] dirs = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
boolean found = false;
for (int i = 0; i < m; i++) {
if (found) break;
for (int j = 0; j < n; j++) {
if (A[i][j] == 1) {
found = true;
dfs(A, i, j, visited, dirs, queue);
break;
}
}
}
int count = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] cur = queue.poll();
for (int[] dir: dirs) {
int x = cur[0]+dir[0], y = cur[1]+dir[1];
if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y]) continue;
if (A[x][y] == 1) return count;
queue.offer(new int[]{x, y});
visited[x][y] = true;
}
}
count++;
}
return -1;
}
private void dfs(int[][] A, int i, int j, boolean[][] visited, int[][] dirs, Queue<int[]> queue) {
int m = A.length, n = A[0].length;
if (i < 0 || i >= m || j < 0 || j >= n || A[i][j] == 0 || visited[i][j]) return;
queue.offer(new int[]{i, j});
visited[i][j] = true;
for (int[] dir: dirs) {
dfs(A, i+dir[0], j+dir[1], visited, dirs, queue);
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。