Shortest Bridge

Try to solve the Shortest Bridge problem.

Statement

We are given an nn ×\times nn 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. Whereas, a cell with a value of 0 represents water. A group of adjacent cells with the value 1 constitutes an island. Two cells are considered adjacent if one of them is above, below, to the left of, or to the right of the second cell. We have 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 100100

  • n==n == grid.length ==== grid[i].length, such that 2≤2 \leq i ≤n\leq n

  • grid[i][j] is either 00 or 11, where 2≤2 \leq i, j ≤n\leq n

  • There are exactly two islands in the grid.

Example

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy