CodeArchon

mediumGraphsAmazonFacebook

Largest Island Surveyor

A geographer ranks landmasses by acreage from a binary satellite map and reports the largest.

Given a binary grid, return the size (in cells) of the largest 4-connected island of 1s.

Choose approach

0
0
1
seed
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
0
0
0
0
1
1
0
1
0
0
0
0
0
0
0
0
0
1
0
0
1
1
0
0
1
0
1
0
0
1/7
Narrationstep 1 of 7

Flooded island starting (0,2) area=1. Best = 1 (new max!).

1def maxAreaOfIsland(g):
2 R, C = len(g), len(g[0])
3 best = 0
4 def dfs(r, c):
5 if r<0 or r>=R or c<0 or c>=C or g[r][c] != 1: return 0
6 g[r][c] = 0
7 return 1 + 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 g[r][c] == 1: best = max(best, dfs(r, c))
11 return best
Variables
area=1
best=1

How to think about it

  1. Flood-fill returns 1 + sum of neighbor floods.
  2. Mutate visited cells to 0 to avoid re-counting.
  3. Max over all starting cells = answer.

Edge cases to catch in interview

  • All water -> 0.
  • Single land cell -> 1.

Examples

Example 13
{"grid":[[1,1],[1,0]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed