SDE & MLE Prep

934. Shortest Bridge

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