You are given an `n x n` binary matrix `grid` where `1` is land and `0` is water. An island is a group of `1`s connected in the four directions, and the grid contains exactly two islands. You may change `0`s into `1`s to join the two islands into one. Return the smallest number of `0`s you must flip.
You are given an n x n binary matrix grid where 1 is land and 0 is water. An island is a group of 1s connected in the four directions, and the grid contains exactly two islands. You may change 0s into 1s to join the two islands into one. Return the smallest number of 0s you must flip.
Example 1:
Input: {"grid":[[0,1],[1,0]]}
Output: 1
Constraints:
n==grid.length==grid[i].length
2≤n≤100
grid[i][j] is either 0 or 1
There are exactly two islands in grid
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"grid":[[0,1],[1,0]]}
Scan row by row for the first land cell. It is (0,1), so it belongs to the island the bridge starts from.