Problem · Array
Count Islands in a Binary Grid
Learn this problemProblem statement
Given a rectangular binary grid, return the number of islands.
Each cell is either 1 for land or 0 for water. An island is a maximal group of land cells connected vertically or horizontally. Diagonal cells are not connected.
Function
countIslands(grid: int[][]) → intExamples
Example 1
grid = [[1,1,0,0],[1,0,0,1],[0,0,1,1],[0,0,0,0]]return = 2The land in the upper-left forms one island. The three connected land cells on the right form a second island.
Example 2
grid = [[0,0,0],[0,0,0]]return = 0The grid contains no land, so it contains no islands.
Example 3
grid = [[1,0,1],[0,1,0],[1,0,1]]return = 5Every land cell touches the others only diagonally. Because diagonal contact does not connect islands, all five land cells are separate.
Constraints
1 <= grid.length <= 300.1 <= grid[r].length <= 300for every rowr.- All rows have the same length.
- Every cell is either
0or1. - The caller does not require the input grid to remain unchanged.