Shortest Bridge Problem: Imagine you're looking at a satellite map of an ocean with exactly two separate islands. You have the power to transform water into land, and your mission is to build the shortest possible bridge between these two islands.

You are given an n x n binary matrix where 1 represents land and 0 represents water. An island is a group of connected land cells (connected horizontally or vertically, not diagonally). The grid is guaranteed to contain exactly two islands.

Your Goal: Find the minimum number of water cells (0s) you need to flip to 1s to connect the two islands into one continuous landmass.

Example: If you have islands at opposite corners, you'd need to create a path of land connecting them. The shortest path requires the fewest water-to-land conversions.

Input & Output

example_1.py โ€” Basic Bridge
$ Input: grid = [[0,1],[1,0]]
โ€บ Output: 1
๐Ÿ’ก Note: Two single-cell islands in opposite corners. We need to flip one water cell to connect them, creating either [[0,1],[1,1]] or [[1,1],[1,0]].
example_2.py โ€” Larger Islands
$ Input: grid = [[0,1,0],[0,0,0],[0,0,1]]
โ€บ Output: 2
๐Ÿ’ก Note: Island 1 is at (0,1) and Island 2 is at (2,2). The shortest path requires flipping 2 water cells: (1,1) and either (1,2) or (2,1).
example_3.py โ€” Connected Islands
$ Input: grid = [[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]]
โ€บ Output: 1
๐Ÿ’ก Note: Large outer island surrounds inner single-cell island. Only need to flip 1 water cell to connect them.

Constraints

  • n == grid.length == grid[i].length
  • 2 โ‰ค n โ‰ค 100
  • grid[i][j] is either 0 or 1
  • Exactly two islands are guaranteed to exist in the grid
  • An island is a 4-directionally connected group of 1's

Visualization

Tap to expand
Ocean with Two IslandsIsland AIsland BLegend:Islands (Land)BFS Starting PointsBridge ExpansionWater (Ocean)BFS ensures we find the shortest possible bridge path
Understanding the Visualization
1
Survey First Island
Use DFS to map out the entire first island and identify all coastal boundary points
2
Multi-Point Expansion
Start construction from ALL coastal points simultaneously using BFS
3
Wave Propagation
Construction expands outward like a wave, one step at a time across the water
4
Bridge Complete
Stop when the expanding wave reaches any point of the second island
Key Takeaway
๐ŸŽฏ Key Insight: Multi-source BFS from all boundary points of one island guarantees finding the shortest bridge to the other island, mimicking how water waves propagate uniformly in all directions.
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 25
41.2K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen