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: 3
💡 Note: Islands at opposite corners (0,0) and (2,2). Shortest 4-directional path requires 3 flips: (0,0) → (1,0) → (1,1) → (1,2) → (2,2), flipping cells (1,0), (1,1), and (1,2).

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 - BFS Approach INPUT Binary Grid (n x n) 0 1 0 0 0 0 0 0 1 Island 1 Island 2 Water (0) grid = [[0,1,0], [0,0,0], [0,0,1]] ALGORITHM STEPS 1 Find First Island DFS to mark all cells of island 1 2 Initialize BFS Queue Add island 1 cells to queue 3 BFS Expansion Expand layer by layer counting distance 4 Find Island 2 Return distance when reaching island 2 I1 d=1 d=2 I2 BFS expands from Island 1 FINAL RESULT 0 1 0 0 1 0 0 1 1 Orange cells = Bridge (flipped 0s to 1s) OUTPUT 2 Minimum flips needed to connect islands = 2 Key Insight: Use DFS to identify and mark the first island, then use BFS to expand from all cells of island 1 simultaneously. BFS guarantees the shortest path, so when we first reach island 2, the distance traveled equals the minimum number of 0s to flip. TutorialsPoint - Shortest Bridge | BFS Approach
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