You are given an n x n binary matrix grid where 1 represents land and 0 represents water.

An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.

You may change 0's to 1's to connect the two islands to form one island.

Return the smallest number of 0's you must flip to connect the two islands.

Input & Output

Example 1 — Basic 3x3 Grid
$ Input: grid = [[0,1,0],[0,0,0],[0,0,1]]
Output: 2
💡 Note: Island 1 is at (0,1), Island 2 is at (2,2). Shortest path: (0,1) → (1,1) → (1,2) → (2,2), requiring 2 flips at (1,1) and (1,2).
Example 2 — Adjacent 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 island at (2,2). Only need to flip one adjacent cell like (1,2) or (2,1) to connect them.
Example 3 — Corner Islands
$ Input: grid = [[1,0,0],[0,0,0],[0,0,1]]
Output: 4
💡 Note: Islands at opposite corners (0,0) and (2,2). Manhattan distance is |0-2| + |0-2| - 1 = 3, but need 4 flips for 4-directional path.

Constraints

  • n == grid.length == grid[i].length
  • 2 ≤ n ≤ 100
  • grid[i][j] is either 0 or 1
  • There are exactly two islands in grid

Visualization

Tap to expand
Shortest Bridge: Connect Two IslandsInput Grid010000001Shortest Bridge Path11001001Result2Island 1: (0,1)Island 2: (2,2)Bridge cells to flipFlips neededPath: (0,1) → (1,1) → (1,2) → (2,2)Bridge length: 2 (flip cells at (1,1) and (1,2))
Understanding the Visualization
1
Input Grid
Binary matrix with exactly two separate islands
2
Find Bridge
Calculate shortest path between island boundaries
3
Output Length
Return minimum number of 0s to flip
Key Takeaway
🎯 Key Insight: Use multi-source BFS from island boundary to find shortest water crossing
Asked in
Amazon 15 Google 12 Facebook 8 Microsoft 6
89.0K Views
Medium Frequency
~25 min Avg. Time
2.1K 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