A rectangular island borders the Pacific Ocean (top and left edges) and the Atlantic Ocean (bottom and right edges). heights[r][c] is the elevation. Water flows from a cell to an equal-or-lower neighbor. Find all cells from which water can flow to both oceans.
1 ≤ heights.length, heights[r].length ≤ 1000 ≤ heights[r][c] ≤ 1000Forward: "can water from (r,c) reach the ocean?" requires a full DFS/BFS per cell → O((m·n)²). Reverse: start from the ocean border, climb uphill. Any reachable cell means water flows back down. Two multi-source BFS runs → O(m·n) total.
heights[nr][nc] ≥ heights[r][c].| Approach | Time | Space | Notes |
|---|---|---|---|
| Brute Force (per-cell DFS) | O((m·n)²) | O(m·n) | TLE on large grids |
| Reverse Multi-source BFS ✓ | O(m·n) | O(m·n) | Two passes, optimal |
■ Blue = Pacific reachable · ■ Red = Atlantic reachable · ■ Green = BOTH (answer) · Numbers = cell heights
For each cell, run a separate DFS checking if water can flow to both oceans. Correct but too slow for large grids.
def pacificAtlantic(self, heights):
ROWS, COLS = len(heights), len(heights[0])
pacific = atlantic = False
def dfs(r, c, prevVal):
nonlocal pacific, atlantic
if r < 0 or c < 0: pacific = True; return
if r >= ROWS or c >= COLS: atlantic = True; return
if heights[r][c] > prevVal: return
tmp = heights[r][c]
heights[r][c] = float('inf') # mark visited
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1)]:
dfs(r+dx, c+dy, tmp)
if pacific and atlantic: break
heights[r][c] = tmp # restore
res = []
for r in range(ROWS):
for c in range(COLS):
pacific = atlantic = False
dfs(r, c, float('inf'))
if pacific and atlantic:
res.append([r, c])
return res # O((m*n)^2) — TLE on large inputsIn the reversed BFS, the condition is heights[nr][nc] ≥ heights[r][c] (climbing uphill/flat). Using ≤ instead gives the wrong direction — you'd be following downhill paths away from the ocean, not toward the interior.
Corner cells (e.g., (0,0) and (ROWS-1, COLS-1)) border two oceans each. The seeding loop handles them naturally — (0,0) is added by the top-row loop for Pacific; (ROWS-1,COLS-1) by the bottom-row loop for Atlantic. No special casing needed.
The brute force O((m·n)²) approach is too slow for 100×100 grids. Always use the reversed multi-source approach — two BFS runs total, not one per cell.
Discussion
…