Number of Islands
Problem statement
Return the number of islands in a rectangular binary grid. An island is a maximal group of land cells connected through shared horizontal or vertical edges. Diagonal contact does not connect islands.
For this exercise, integer 1 means land and 0 means water. The outside of the grid is water. An empty grid or zero-column grid has zero islands. You may modify the input grid.
Function
numIslands(grid: int[][]) → intExamples
Example 1
grid = [[1,1,0],[0,1,0],[1,0,1]]return = 3The cells [0,0], [0,1] and [1,1] form one island. Cells [2,0] and [2,2] each form a separate island, for three total.
Example 2
grid = [[0,0],[0,0]]return = 0Every cell is water, so the count is zero.
Constraints
0 <= grid.length <= 300 <= grid[r].length <= 30- All rows have the same length.
0 <= grid[r][c] <= 1