mediumGraphBFSDFSGraphs

Shortest Bridge

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

Signals to notice

connect two islandsfind shortest bridgemulti-source BFS from one island

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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