CodeArchon

mediumGraphsFacebookGoogle

Watershed Divide

A hydrology grid identifies cells whose rainwater can flow to BOTH the Pacific (top/left borders) and Atlantic (bottom/right borders) along downhill-only paths.

Given an m×n matrix of heights, return all coordinates whose water can flow to both the top/left and bottom/right ocean borders.

Choose approach

1P
2P
2P
3P
5★
3P
2P
3P
4★
4★
2P
4P
5★
3A
1A
6★
7★
1A
4A
5A
5★
1A
1A
2A
4A
1/1
Narrationstep 1 of 1

Reverse flow from Pacific borders (P) and Atlantic borders (A). ★ = reaches both.

1def pacificAtlantic(h):
2 R, C = len(h), len(h[0])
3 pac = [[False]*C for _ in range(R)]
4 atl = [[False]*C for _ in range(R)]
5 def dfs(r, c, v, prev):
6 if r<0 or r>=R or c<0 or c>=C or v[r][c] or h[r][c] < prev: return
7 v[r][c] = True
8 for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]: dfs(r+dr, c+dc, v, h[r][c])
9 for r in range(R):
10 dfs(r, 0, pac, float('-inf')); dfs(r, C-1, atl, float('-inf'))
11 for c in range(C):
12 dfs(0, c, pac, float('-inf')); dfs(R-1, c, atl, float('-inf'))
13 return [[r, c] for r in range(R) for c in range(C) if pac[r][c] and atl[r][c]]
Variables
dualReach=7

How to think about it

  1. Downhill-forward from each cell is quadratic; reverse-uphill from borders is linear.
  2. Each cell is visited at most twice (once per ocean).
  3. Answer = Pacific ∩ Atlantic.

Edge cases to catch in interview

  • Corner cell -> reaches both automatically.
  • Flat heights -> every cell reaches both.

Examples

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

Try your own input

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