Shortest Bridge (LeetCode 934): Solution and Explanation

Medium
Array
Depth First Search
Breadth First Search
Matrix

A square grid holds exactly two islands of land. Find the fewest water cells you must turn into land so that the two islands become connected.

Intuition

The cells you flip form a path of water from one island to the other, so the answer is the length of the shortest such water path. That is a shortest-path question on a grid, which points to BFS.

The path can start from any cell of the first island, not from one fixed cell. Running a BFS from each island cell separately would be slow. Instead, put all of the first island's cells into the queue at distance 0 and let one BFS spread from all of them together. This is a multi-source BFS.

Picture it as a ripple. Level 0 is the island itself. Level 1 is every water cell touching the island, which costs one flip. Level 2 is the water touching level 1, and so on. The first time the ripple bumps into land that is not the first island, the level number is the number of flips.

To start the ripple you first need the whole first island. Scan for any land cell and flood-fill from it, marking each cell so the BFS knows it is the source and does not mistake it for the target island.

Approach: Flood fill, then multi-source BFS

  1. Scan the grid for the first cell with value 1.
  2. Flood-fill its island with a stack (or recursion), changing each cell to 2 and adding it to a queue.
  3. Set steps = 0. Process the queue one level at a time.
  4. For each neighbor of a popped cell: if it is 1, it is the other island, so return steps. If it is 0, change it to 2 and enqueue it.
  5. After finishing a level, increase steps by one.

Step-by-step example

grid = [[0,1],[1,0]]
  1. The first land cell in row order is (0,1). It has no land neighbors, so the first island is just that cell. The queue is [(0,1)].
  2. Level 0: pop (0,1). Its water neighbors (1,1) and (0,0) are marked and queued, each needing one flip.
  3. Level 1: pop (1,1). Its neighbor (1,0) is still 1, so it belongs to the second island.
  4. The ripple reached the second island while expanding level 1, so the answer is 1.

Code: Python, Java, C++

1class Solution:
2    def shortestBridge(self, grid: List[List[int]]) -> int:
3        n = len(grid)
4        dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
5        sr, sc = next((r, c) for r in range(n) for c in range(n) if grid[r][c] == 1)
6        grid[sr][sc] = 2
7        stack = [(sr, sc)]
8        queue = deque()
9        while stack:
10            r, c = stack.pop()
11            queue.append((r, c))
12            for dr, dc in dirs:
13                nr, nc = r + dr, c + dc
14                if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 1:
15                    grid[nr][nc] = 2
16                    stack.append((nr, nc))
17        steps = 0
18        while queue:
19            for _ in range(len(queue)):
20                r, c = queue.popleft()
21                for dr, dc in dirs:
22                    nr, nc = r + dr, c + dc
23                    if 0 <= nr < n and 0 <= nc < n:
24                        if grid[nr][nc] == 1:
25                            return steps
26                        if grid[nr][nc] == 0:
27                            grid[nr][nc] = 2
28                            queue.append((nr, nc))
29            steps += 1
30        return -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

The flood fill and the BFS each visit every cell at most once, and there are n^2 cells.

Space

O(n^2)

The stack and the queue can each hold a large share of the grid in the worst case.

Other approaches

BFS from every cell of the first island separately (time O(n^4), space O(n^2))

Run a separate BFS from each cell of the first island and keep the minimum. Correct but repeats almost the same work for every source cell.

Pairwise Manhattan distance (time O(|A| * |B|), space O(n^2))

Collect both islands' cells and take the minimum Manhattan distance minus one over all pairs. Works because water has no obstacles, but it is quadratic in the island sizes.

Common mistakes

  • Starting the BFS from a single island cell. The shortest bridge can leave from any cell of the island, so all of them must be sources at level 0.
  • Forgetting to mark the first island before the BFS. Its own unmarked cells would look like the second island and the answer would be 0.
  • Returning steps + 1. The level counter already equals the number of water cells between the popped cell and the island.
  • Recursive flood fill in Python on a 100 x 100 island can exceed the recursion limit. An explicit stack avoids that.

Frequently asked questions

Why is BFS enough without Dijkstra?

Every flip costs exactly 1, so the graph is unweighted. BFS visits cells in order of distance, which is exactly what Dijkstra would do with equal weights.

Does it matter which island I flood-fill first?

No. The shortest distance between the two islands is the same in both directions, so starting from either one gives the same answer.

Can I avoid modifying the input grid?

Yes. Use a separate visited matrix instead of writing 2 into the grid. The algorithm and complexity stay the same.