Problem
Ask
Submissions

Problem: Shortest Bridge

Medium
30 min
Explore how to solve the shortest bridge problem in a binary n by n grid by flipping the least zeros to connect two islands. Understand adjacency concepts and apply efficient algorithms running in O(n²) time. This lesson helps you practice algorithm design and problem-solving skills essential 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.

Problem
Ask
Submissions

Problem: Shortest Bridge

Medium
30 min
Explore how to solve the shortest bridge problem in a binary n by n grid by flipping the least zeros to connect two islands. Understand adjacency concepts and apply efficient algorithms running in O(n²) time. This lesson helps you practice algorithm design and problem-solving skills essential 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.