[LeetCode] Problem 934 - Shortest Bridge

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

No.1

Input: [[0,1],[1,0]]

Output: 1

No.2

Input: [[0,1,0],[0,0,0],[0,0,1]]

Output: 2

No.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. 1 <= A.length = A[0].length <= 100
  2. A[i][j] == 0 or A[i][j] == 1

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public int shortestBridge(int[][] A) {
int result = 0;
int m = A.length;
int n = A[0].length;
int[][] directions = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
Queue<int[]> queue = new LinkedList<>();

findIsland:
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (A[i][j] == 1) {
dfs(queue, A, i, j, m, n);
break findIsland;
}
}
}

while (!queue.isEmpty()) {
int size = queue.size();

for (int i = 0; i < size; i++) {
int[] pos = queue.poll();

for (int[] direction : directions) {
int x = pos[0] + direction[0];
int y = pos[1] + direction[1];

if (x < 0 || y < 0 || x >= m || y >= n || A[x][y] == 2)
continue;

if (A[x][y] == 1)
return result;

A[x][y] = 2;
queue.offer(new int[] {x, y});
}
}

result++;
}

return -1;
}

private void dfs(Queue<int[]> queue, int[][] A, int x, int y, int m, int n) {
if (x < 0 || y < 0 || x >= m || y >= n || A[x][y] != 1)
return;

queue.offer(new int[] {x, y});
A[x][y] = 2;
dfs(queue, A, x + 1, y, m, n);
dfs(queue, A, x - 1, y, m, n);
dfs(queue, A, x, y + 1, m, n);
dfs(queue, A, x, y - 1, m, n);
}