mediumGraphsAmazonFacebookGoogle
Island Census
A cartographer counts contiguous landmasses on a satellite grid where '1' = land and '0' = water.
Given an m×n grid of '1' (land) and '0' (water), return the number of islands. Islands are connected 4-directionally.
Choose approach
1
cur
1
0
0
0
1
1
0
0
0
0
0
1
0
0
0
0
0
1
1
1/11
Narrationstep 1 of 11
Discover new island #1 at (0,0).
Variables
islands=1
r=0
c=0
How to think about it
- Each flood touches a cell at most once -> linear total work.
- Mutating the grid is cheaper than a separate visited set.
- BFS variant avoids recursion stack blow-ups on huge grids.
Edge cases to catch in interview
- All water -> 0.
- Single row -> runs merge into one island each.
Examples
Example 1
2{"grid":[["1","1","0"],["0","1","0"],["0","0","1"]]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed