sagelearnai

Shortest Bridge

Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #934

An n × n binary grid contains exactly two islands (4-connected groups of 1s). Return the minimum number of 0s you must flip to 1 to connect them.

Examples

text
[[0,1],[1,0]]                           →  1
[[0,1,0],[0,0,0],[0,0,1]]               →  2
[[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

Hints

  1. First find one island completely. Any DFS from any 1 does it.
  2. Then expand from all of its cells at once, layer by layer. The layer at which you first touch a 1 not in island A is the answer.

Approach

  1. Find the first 1, DFS its whole island, mark it with 2, and add every cell to a queue.
  2. Multi-source BFS from that queue. Each layer is one more flipped water cell. When a neighbor is a 1 (the other island), return the current layer count. Mark visited water as 2 so it isn't revisited.

Combining DFS (to collect a component) with BFS (to measure distance from it) is a recurring pattern.

Complexity

Time: O(n²). Space: O(n²).

Python solution
from collections import deque

def shortestBridge(grid):
    n = len(grid)
    q = deque()
    def first():
        for r in range(n):
            for c in range(n):
                if grid[r][c] == 1:
                    return r, c
    sr, sc = first()
    stack = [(sr, sc)]
    grid[sr][sc] = 2
    while stack:
        r, c = stack.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
                stack.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
    return -1
JavaScript solution
function shortestBridge(grid) {
  const n = grid.length, dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  let sr = -1, sc = -1;
  outer: for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) if (grid[r][c] === 1) { sr = r; sc = c; break outer; }
  let q = [];
  const stack = [[sr, sc]]; grid[sr][sc] = 2;
  while (stack.length) {
    const [r, c] = stack.pop(); q.push([r, c]);
    for (const [dr, dc] of dirs) { const nr = r + dr, nc = c + dc; if (nr >= 0 && nc >= 0 && nr < n && nc < n && grid[nr][nc] === 1) { grid[nr][nc] = 2; stack.push([nr, nc]); } }
  }
  for (let steps = 0; q.length; steps++) {
    const next = [];
    for (const [r, c] of q) for (const [dr, dc] of dirs) {
      const nr = r + dr, nc = c + dc;
      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; next.push([nr, nc]); }
    }
    q = next;
  }
  return -1;
}