CodeArchon

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).

1def numIslands(grid):
2 R, C = len(grid), len(grid[0])
3 count = 0
4 def dfs(r, c):
5 if r<0 or r>=R or c<0 or c>=C or grid[r][c] != '1': return
6 grid[r][c] = '0'
7 dfs(r+1,c); dfs(r-1,c); dfs(r,c+1); dfs(r,c-1)
8 for r in range(R):
9 for c in range(C):
10 if grid[r][c] == '1':
11 count += 1; dfs(r, c)
12 return count
Variables
islands=1
r=0
c=0

How to think about it

  1. Each flood touches a cell at most once -> linear total work.
  2. Mutating the grid is cheaper than a separate visited set.
  3. 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 12
{"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