Search⌘ K
AI Features

Shortest Bridge

Explore how to identify and connect two islands in a binary grid by flipping the fewest 0s to 1s. Learn techniques to analyze grid-based problems and implement solutions that run in optimal O(n²) time and space. This lesson deepens understanding of adjacency and traversal in matrix challenges, improving problem-solving skills for coding interviews.

Statement

We are given an n×nn×n binary matrix grid containing 0s and 1s. Each cell in the grid represents either land or water. A cell with a value of 1 represents land, while a cell with a value of 0 represents water. A group of adjacent cells with a value of 1 constitutes an island. Two cells are considered adjacent if one is above, below, to the left, or to the right of the other. Our task is to return the smallest number of 0s we must flip to connect the two islands.

Note: We may assume all four edges of the grid are surrounded by water.

Constraints:

  • 22 \leq n \leq 2020

  • n==n == grid.length ==== grid[i].length.

  • grid[i][j] is either 0 or 1.

  • There are exactly two islands in the grid.

Example

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:

Shortest Bridge

1.

What is the smallest number of 0s we must flip to connect the two islands if the following matrix is given?

[[0,1,0,0,0]
[0,1,0,0,0]
[1,1,0,0,1]
[0,0,0,0,1]
[0,0,0,0,1]] 
A.

1

B.

2

C.

3

D.

None of the above


1 / 2

Try it yourself

Implement your solution in the following coding playground:

The optimal solution to this problem runs in O(n2) time and takes O(n2) space.

Go
usercode > main.go
package main
func shortestBridge(grid [][]int) int {
// Replace this placeholder return statement with your code
return -1
}
Shortest Bridge