grid of size n × n, where 1 is land and 0 is water. An island is a group of land cells connected through their sides (not diagonally). The map has exactly two islands.
To join them you may fill water cells, turning them into land. Return the smallest number of cells you must fill so that the two islands become one.grid=[[1, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1]] → 3
For example, fill (1, 1), (1, 2) and (2, 2): three water cells link the island in the top-left corner with the one in the bottom right. Fewer is not enough.
grid=[[1, 0, 1], [1, 0, 1], [1, 0, 1]] → 1
Two vertical strips of land are split by a single water column, so filling one cell is enough.
grid=[[1, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1]]
3
Run checks the first 3 tests in your browser. Submit checks all 16 tests on the server, hidden ones included.