Pacific Atlantic Water Flow
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #417
heights is a grid of land elevations. The Pacific touches the top and left edges; the Atlantic touches the bottom and right edges. Rain flows from a cell to a 4-directional neighbor whose height is less than or equal to it, and from border cells into the adjacent ocean. Return all cells [r, c] from which water can reach both oceans (any order).
Example
heights = [[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]
→ [[0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]]Hints
- Simulating flow from every cell is slow. Reverse the direction instead.
- From the ocean's border, move "uphill" to neighbors with height ≥ current. Every cell you reach can drain to that ocean.
- Do this once for each ocean and intersect the two sets.
Approach
Run two multi-source traversals: one starting from all Pacific border cells (top row and left column), one from all Atlantic border cells (bottom row and right column). From a cell, move to neighbors whose height is ≥ the current height, which is the reverse of the downhill flow. Collect the reachable sets P and A; the answer is P ∩ A. Each traversal is O(R·C).
Complexity
Time: O(R·C). Space: O(R·C).
Python solution
from collections import deque
def pacificAtlantic(heights):
R, C = len(heights), len(heights[0])
def reach(starts):
seen = set(starts)
q = deque(starts)
while q:
r, c = q.popleft()
for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if 0 <= nr < R and 0 <= nc < C and (nr, nc) not in seen and heights[nr][nc] >= heights[r][c]:
seen.add((nr, nc))
q.append((nr, nc))
return seen
pac = reach([(0, c) for c in range(C)] + [(r, 0) for r in range(R)])
atl = reach([(R - 1, c) for c in range(C)] + [(r, C - 1) for r in range(R)])
return [[r, c] for r, c in pac & atl]JavaScript solution
function pacificAtlantic(heights) {
const R = heights.length, C = heights[0].length;
const reach = (starts) => {
const seen = new Set(starts.map(([r, c]) => r * C + c)); const q = [...starts];
for (let h = 0; h < q.length; h++) {
const [r, c] = q[h];
for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
if (nr >= 0 && nc >= 0 && nr < R && nc < C && !seen.has(nr * C + nc) && heights[nr][nc] >= heights[r][c]) { seen.add(nr * C + nc); q.push([nr, nc]); }
}
}
return seen;
};
const pS = [], aS = [];
for (let c = 0; c < C; c++) { pS.push([0, c]); aS.push([R - 1, c]); }
for (let r = 0; r < R; r++) { pS.push([r, 0]); aS.push([r, C - 1]); }
const P = reach(pS), A = reach(aS), out = [];
for (const k of P) if (A.has(k)) out.push([Math.floor(k / C), k % C]);
return out;
}