You are given a binary grid with 0s (water) and 1s (land). An island is a group of connected 1s using four directions (up, down, left, and right). You need to return the minimum number of 0s that must be flipped to connect two islands (i.e., make the two islands have the same set of connected land).
Example 1:
Input: grid = [ [0,1,0], [1,0,1], [0,0,0] ] Output: 1
Explanation:
We need to flip at least one 0 to connect the two islands, and the flipped grid would look like this:
[ [0,1,0], [1,1,1], [0,0,0] ]
Example 2:
Input: grid = [ [1,1,0,0], [0,0,0,1], [0,1,0,0], [1,0,1,0] ] Output: 0
Explanation:
We do not need to flip any 0s to connect the two islands because they are already connected.
Example 3:
Input: grid = [ [1, 0, 0], [0, 0, 1], [1, 0, 1] ] Output: 2
Explanation:
We need to flip two 0s to connect the islands, and the flipped grid would look like this:
[ [1, 0, 0], [0, 1, 1], [1, 0, 1] ]
1 <= grid.length <= 10001 <= grid[0].length <= 1000