Shortest Bridge

You are given an `n x n` binary matrix `grid` where `1` is land and `0` is water. An island is a group of `1`s connected in the four directions, and the grid contains exactly two islands. You may change `0`s into `1`s to join the two islands into one. Return the smallest number of `0`s you must flip.

30:00

Shortest Bridge
medium
Free written solution
Topics
Companies

You are given an n x n binary matrix grid where 1 is land and 0 is water. An island is a group of 1s connected in the four directions, and the grid contains exactly two islands. You may change 0s into 1s to join the two islands into one. Return the smallest number of 0s you must flip.

Example 1:
Input: {"grid":[[0,1],[1,0]]}
Output: 1
Constraints:
  • n==grid.length==grid[i].lengthn == \text{grid.length} == \text{grid}[i].\text{length}

  • 2≤n≤1002 \leq n \leq 100

  • grid[i][j]\text{grid}[i][j] is either 00 or 11

  • There are exactly two islands in grid\text{grid}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[0,1],[1,0]]}

Scan row by row for the first land cell. It is (0,1), so it belongs to the island the bridge starts from.

island A

1

ripple

-

queue

0

flips

...

A

first island (ripple source)

other land

water reached, number = flips

bridge

Variables
VariableValue
start(0,1)
DepthFunction Call
Stack empty
0/4