Shortest Bridge

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.

Example 1
0 1
1 0
Inputgrid = [[0,1],[1,0]]
Output1
Flipping one water cell connects the two diagonal land cells into one island.
Example 2
0 1 0
0 0 0
0 0 1
Inputgrid = [[0,1,0],[0,0,0],[0,0,1]]
Output2
Flipping two water cells creates a path connecting the two islands.

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.

Asked at 15 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate