Asked at
Number of Islands
MediumVerifiedBFSDFSMatrixUnion Find~20 min
You’re given a grid of 0 (water) and 1 (land). An island is a maximal group of land cells connected 4-directionally.
Return the number of islands. The input is the grid number[][] directly.
Examples
in[[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]
out3
Three separate land masses.
in[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]]
out1
All land cells connect into one island.
Constraints
- 1 ≤ rows, cols ≤ 300
- grid[r][c] is 0 (water) or 1 (land).
- Islands connect 4-directionally.
Get help
🔑
Sign in to solve
Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.