934.Shortest Bridge
Problem description:
In a given 2D binary array grid
, there are two islands. (An island is a 4-directionally connected group of 1
s not connected to any other 1s.)
Now, we may change 0
s to 1
s so as to connect the two islands together to form 1 island.
Return the smallest number of 0
s that must be flipped. (It is guaranteed that the answer is at least 1.)
Example 1:
1 | Input: grid = [[0,1],[1,0]] |
Example 2:
1 | Input: grid = [[0,1,0],[0,0,0],[0,0,1]] |
Example 3:
1 | Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] |
Constraints:
2 <= grid.length == grid[0].length <= 100
grid[i][j] == 0
orgrid[i][j] == 1
Solution:
We first paint one of the islands using DFS with color 2, so we can easily identify island #1 and island #2.
Then we start expanding island #2 by paining connected empty area. Each round, we increase the color (3, 4, and so on) so we can keep track of the newly painted area. This ends when we “bump” into the first island.
The fact that we are increasing the color is also useful for the backtracking, if we need to return the coordinates of the bridge.
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: