Shortest Bridge - Problem
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code