CodingMedium
Number of Islands
You’re given an m by n grid where each cell is 1 for land or 0 for water. Return the number of islands.
An island is a group of land cells connected horizontally or vertically, never diagonally. Everything beyond the grid’s edges is water.
Example 1
Input
grid = [
[1,1,0,0,1],
[1,0,0,1,1],
[0,0,0,0,0],
[0,1,1,0,1]
]Output4Two islands along the top, a pair of cells in the bottom row, and a single cell in the bottom-right corner.
Example 2
Input
grid = [[1,0],[0,1]]Output2Cells that touch only at a corner aren’t connected.
Constraints
- 1 ≤ m, n ≤ 300
- grid[i][j] is 0 or 1