1. Reachability grid
Track which cells can reach each ocean.
const pacific = Array.from({ length: rows }, () => new Array(cols).fill(false))Typorithm · medium
Step 1 of 8 · intro card
Graphs
Reverse the flow: DFS inward from each ocean's border climbing uphill, then return cells reachable from BOTH oceans.
Simulating downhill flow from every cell is expensive; instead, reverse it and flow up from the oceans.
From each ocean's border, DFS to any neighbor at least as high, marking reachable cells.
A cell drains to both oceans exactly when both reachability grids mark it.
Reverse the flow from the borders.
Climb to equal-or-higher cells.
Answer = reachable by both oceans.
function pacificAtlantic(heights) {
const rows = heights.length;
const cols = heights[0].length;
const pacific = Array.from({ length: rows }, () => new Array(cols).fill(false));
const atlantic = Array.from({ length: rows }, () => new Array(cols).fill(false));
function dfs(r, c, seen, prev) {
if (r < 0 || c < 0 || r >= rows || c >= cols || seen[r][c] || heights[r][c] < prev) {
return;
}
seen[r][c] = true;
dfs(r + 1, c, seen, heights[r][c]);
dfs(r - 1, c, seen, heights[r][c]);
dfs(r, c + 1, seen, heights[r][c]);
dfs(r, c - 1, seen, heights[r][c]);
}
for (let r = 0; r < rows; r += 1) {
dfs(r, 0, pacific, -Infinity);
dfs(r, cols - 1, atlantic, -Infinity);
}
for (let c = 0; c < cols; c += 1) {
dfs(0, c, pacific, -Infinity);
dfs(rows - 1, c, atlantic, -Infinity);
}
const result = [];
for (let r = 0; r < rows; r += 1) {
for (let c = 0; c < cols; c += 1) {
if (pacific[r][c] && atlantic[r][c]) {
result.push([r, c]);
}
}
}
return result;
}Connect each part of the code to the concept before you type.
Track which cells can reach each ocean.
const pacific = Array.from({ length: rows }, () => new Array(cols).fill(false))Reversing flow, move only to cells at least as high.
heights[r][c] < prevSeed DFS from the border cells touching each ocean.
dfs(r, 0, pacific, -Infinity);
dfs(r, cols - 1, atlantic, -Infinity)Answer cells flow to the Pacific AND the Atlantic.
if (pacific[r][c] && atlantic[r][c]) {Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.