Number of Islands

Medium

grid contains 1s (land) and 0s (water). An island is land connected horizontally or vertically.

Return the number of islands.

Example 1

numIslands()
Input
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
Output
1

Example 2

numIslands()
Input
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output
3
Constraints
1 <= m, n <= 300
Every cell is `"0"` or `"1"`.

Topics

MatrixDepth-First SearchBreadth-First SearchUnion Find

Implement numIslands in the editor and return the answer — printing it is never graded.