934. Shortest Bridge
Asked at 16Meta41Google22Amazon22Bloomberg14Microsoft12McKinsey100Tower Research Capital100Coupang87ByteDance71Tesla62Uber59TikTok56Flipkart43Snowflake39Salesforce28Goldman Sachs21
Problem
The n×n binary grid contains exactly two islands (groups of 1s connected up, down, left, right). Return the fewest 0s you must flip to 1 to join them into one island.
Example: [[0,1,0],[0,0,0],[0,0,1]] → 2
Constraints: n ≤ 100.
Find one island with DFS and mark it; then multi-source BFS from all its cells across water. The BFS level at which you first touch the other island is the number of flips.
Complexity: O(n²).
class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
n = len(grid)
start = next((r, c) for r in range(n) for c in range(n) if grid[r][c])
q, st = deque(), [start]
grid[start[0]][start[1]] = 2
while st: # mark island A as 2
r, c = st.pop()
q.append((r, c))
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 1:
grid[nr][nc] = 2
st.append((nr, nc))
steps = 0
while q:
for _ in range(len(q)):
r, c = q.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < n and 0 <= nc < n:
if grid[nr][nc] == 1:
return steps
if grid[nr][nc] == 0:
grid[nr][nc] = 2
q.append((nr, nc))
steps += 1
assert Solution().shortestBridge([[0, 1], [1, 0]]) == 1
assert Solution().shortestBridge([[0, 1, 0], [0, 0, 0], [0, 0, 1]]) == 2
assert Solution().shortestBridge([[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
class Solution {
public int shortestBridge(int[][] grid) {
int n = grid.length;
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
Deque<int[]> q = new ArrayDeque<>(), st = new ArrayDeque<>();
outer:
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++)
if (grid[r][c] == 1) { grid[r][c] = 2; st.push(new int[]{r, c}); break outer; }
while (!st.isEmpty()) {
int[] cur = st.pop();
q.add(cur);
for (int[] d : dirs) {
int nr = cur[0] + d[0], nc = cur[1] + d[1];
if (nr >= 0 && nc >= 0 && nr < n && nc < n && grid[nr][nc] == 1) { grid[nr][nc] = 2; st.push(new int[]{nr, nc}); }
}
}
for (int steps = 0; !q.isEmpty(); steps++)
for (int k = q.size(); k > 0; k--) {
int[] cur = q.poll();
for (int[] d : dirs) {
int nr = cur[0] + d[0], nc = cur[1] + d[1];
if (nr < 0 || nc < 0 || nr >= n || nc >= n) continue;
if (grid[nr][nc] == 1) return steps;
if (grid[nr][nc] == 0) { grid[nr][nc] = 2; q.add(new int[]{nr, nc}); }
}
}
return -1;
}
}
func shortestBridge(grid [][]int) int {
n := len(grid)
dirs := [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
var start [2]int
for r := 0; r < n; r++ {
for c := 0; c < n; c++ {
if grid[r][c] == 1 {
start = [2]int{r, c}
}
}
}
q, st := [][2]int{}, [][2]int{start}
grid[start[0]][start[1]] = 2
for len(st) > 0 { // mark one island as 2; it seeds the BFS
p := st[len(st)-1]
st = st[:len(st)-1]
q = append(q, p)
for _, d := range dirs {
nr, nc := p[0]+d[0], p[1]+d[1]
if nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 1 {
grid[nr][nc] = 2
st = append(st, [2]int{nr, nc})
}
}
}
for steps := 0; len(q) > 0; steps++ { // expand over water until the other island
next := [][2]int{}
for _, p := range q {
for _, d := range dirs {
nr, nc := p[0]+d[0], p[1]+d[1]
if nr < 0 || nr >= n || nc < 0 || nc >= n {
continue
}
if grid[nr][nc] == 1 {
return steps
}
if grid[nr][nc] == 0 {
grid[nr][nc] = 2
next = append(next, [2]int{nr, nc})
}
}
}
q = next
}
return -1
}