Count Four-Neighbor Islands
Problem statement
Given a rectangular grid of 0 (water) and 1 (land), count its islands.
For this practice, land cells belong to the same island when connected through their top, bottom, left, or right sides. Diagonally touching cells are separate unless a path of side-connected land joins them. Each land cell belongs to exactly one island. Return 0 for an empty grid.
Function
numIslands(grid: int[][]) → intExamples
Example 1
grid = [[1,1,0],[0,1,0],[0,0,1]]return = 2The three connected upper-left land cells form one island, and the lower-right cell forms another.
Example 2
grid = [[1,0],[0,1]]return = 2The two land cells meet only diagonally, so they form two islands.
Example 3
grid = []return = 0There are no land cells in an empty grid.
Constraints
0 <= grid.length <= 50.- When the grid is nonempty, every row has the same length between
1and50. - Every cell is
0or1. - The input grid need not be modified.