mediumGraphBFSDFSGraphs

Shortest Bridge

mediumTime: O(n^2)Space: O(n^2)

Recognize the pattern

connect two islandsfind shortest bridgemulti-source BFS from one island

Brute force idea

A straightforward first read of Shortest Bridge is this: For each cell of island 1, BFS to each cell of island 2, take minimum. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The deeper shift in Shortest Bridge is this: DFS to find one island and mark all its cells. Then BFS from all cells of that island simultaneously. The first time BFS reaches a cell of the other island is the shortest bridge. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Shortest Bridge is one steady idea: Multi-source BFS from all cells of island 1 expands outward uniformly. The first cell of island 2 reached gives the minimum distance — no need to check all pairs. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

One easy way to drift off course in Shortest Bridge is this: Not distinguishing the two islands — use DFS to find and mark island 1 first, then BFS treats unmarked land cells as water to cross. The fix is usually to return to the meaning of each move, not just the steps themselves.

Graphs Pattern