Shortest Bridge
Explore how to find the shortest bridge between two islands in a binary matrix by flipping the fewest water cells. Understand the problem constraints and implement an efficient O(n²) solution to connect the islands, enhancing your skills in grid traversal and algorithm optimization.
We'll cover the following...
Statement
We are given an 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:
-
n -
grid.lengthgrid[i].length. -
grid[i][j]is either0or1. -
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
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]]
1
2
3
None of the above
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.
import collectionsdef shortest_bridge(grid):# Replace this placeholder return statement with your codereturn -1