Find all height-grid cells from which water can reach both of two opposite ocean borders.
Problem
Input. A rectangular integer height grid heights.
Output. Return zero-based [row, col] coordinates of every cell with a route to each ocean.
Rules. The Pacific touches the top and left borders; the Atlantic touches the bottom and right borders.
Water moves to equal or lower orthogonal neighbors, never diagonally or uphill.
The two routes may differ. Border cells already touch their corresponding ocean.
Preserve the grid. Empty input returns []; the reference orders coordinates by row, then column.
Example. For this grid:
1 2 2
3 2 3
2 4 1
Return [[0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1]].
This asks reachability, not water volume or travel time.
Picture
Instead of searching from every cell, start at the destinations and walk backward along allowed edges.
If high cell u can flow to neighbor v, the reverse search at v can reach u.
Reverse movement therefore requires neighbor_height >= current_height.
For example, (1,1) -> (0,1) -> (0,2) is a forward level-height route to the Atlantic.
Its reverse (0,2) -> (0,1) -> (1,1) certifies the same reachability.
| Reverse search | Reached cells | Only missing cell |
|---|---|---|
| Pacific | 8 | (2,2) |
| Atlantic | 8 | (0,0) |
Intersect the sets to retain exactly the cells with both certificates.
Problem trace
Reverse search climbs to cells whose water can flow down to the ocean
Reference drawing
Problem trace
Reverse search climbs to cells whose water can flow down to the ocean
Execution trace
- P seed
- (0, 0)
- P seed
- (0, 1)
- P seed
- (0, 2)
- P via 2<
- not shown→(1, 1)
- P via 2<
- not shown→(1, 2)
- P via 2<
- not shown→(2, 1)
- A seed
- not shown→(2, 2)
- P seed
- (0, 0)→not shown
- P seed
- (0, 1)→not shown
- A
- not shown→(0, 1)
- A
- not shown→(1, 0)
- frontier
- not shown→(0,1),(1,0)
- A
- not shown→(1, 1)
- frontier
- (0,1),(1,0)→(1,1)
- reached
- 7 cells→8 cells
- A seed
- (2, 2)→not shown
- result
- not shown→[[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1]]
- search
- Atlantic→not shown
- Recognize it
- Many grid cells ask whether they can reach either of two fixed boundary goals; reversing the edges lets each goal share one traversal across all possible starts.
- Keep true
- Each ocean’s seen set contains exactly cells with a nonincreasing forward path to that ocean. Reverse traversal may move only to an equal-or-higher neighbor, preserving that path witness.
- Reuse it
- When many sources query reachability to a small set of goals, reverse the graph, traverse once from each goal class, and combine the resulting reachable sets.
Seed every border cell for an ocean before traversing. Mark on discovery so each cell enters that ocean’s stack once. Keep the oceans’ sets separate: one combined seed set would certify either, not both.
Code
def pacific_atlantic(heights: list[list[int]]) -> list[list[int]]:
if not heights or not heights[0]:
return []
rows, cols = len(heights), len(heights[0])
def reachable(starts: set[tuple[int, int]]) -> set[tuple[int, int]]:
seen = set(starts)
stack = list(starts)
while stack:
row, col = stack.pop()
for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
next_cell = row + row_step, col + col_step
next_row, next_col = next_cell
if not (0 <= next_row < rows and 0 <= next_col < cols):
continue
if next_cell in seen or heights[next_row][next_col] < heights[row][col]:
continue
seen.add(next_cell)
stack.append(next_cell)
return seen
pacific = {(row, 0) for row in range(rows)} | {(0, col) for col in range(cols)}
atlantic = {(row, cols - 1) for row in range(rows)} | {
(rows - 1, col) for col in range(cols)
}
return [list(cell) for cell in sorted(reachable(pacific) & reachable(atlantic))]
For , the searches use time and space without changing heights.
The literal reference sorts its intersection cells.
Whole-function time is therefore , not unconditionally linear.
Empty or zero-width input returns [].
Failure Check
Searching downhill from the borders follows the wrong edges. Strictly uphill search also fails: equal-height plateau routes are allowed. One shared visited set cannot distinguish the two required destination classes.
Change the Goals
New task: Find cells that can flow to any member of an arbitrary valid goal set.
Picture and change: Reverse from those goals, then emit reached cells by row-major membership scan instead of sorting. Duplicate goals are coalesced; an empty goal set reaches nothing.
def reverse_reached_cells(heights, starts):
if not heights or not heights[0]:
return []
rows, cols = len(heights), len(heights[0])
seen = {tuple(cell) for cell in starts}
stack = list(seen)
while stack:
row, col = stack.pop()
for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
next_row, next_col = row + row_step, col + col_step
cell = next_row, next_col
if 0 <= next_row < rows and 0 <= next_col < cols:
if cell not in seen and heights[next_row][next_col] >= heights[row][col]:
seen.add(cell)
stack.append(cell)
return [[row, col] for row in range(rows) for col in range(cols) if (row, col) in seen]
Check: [[1,2],[3,1]], goal (0,0), returns [[0,0],[0,1],[1,0]].
The lower-right basin cannot reach that goal.
For supplied goals, time is and auxiliary space is .
Heights remain unchanged.
Use when: Many origin cells share arbitrary destinations, including interior outlets.
Change Both to Either
New task: Reaching at least one ocean is sufficient.
Picture and change: Combine all border goals before one reverse traversal, computing a union rather than an intersection.
def reaches_either_ocean(heights):
if not heights or not heights[0]:
return []
rows, cols = len(heights), len(heights[0])
borders = (
{(row, 0) for row in range(rows)}
| {(row, cols - 1) for row in range(rows)}
| {(0, col) for col in range(cols)}
| {(rows - 1, col) for col in range(cols)}
)
return reverse_reached_cells(heights, borders)
Check: A 3x3 grid with border height 3 and center height 1 returns only its eight border cells.
Either-ocean reachability does not include every basin.
Time and space are , including deterministic row-major output.
Use when: The goal combination changes from AND to OR.
Transfer Check
What changes if three goal classes must each be reachable?
Answer
Run one reverse search per class, then intersect all three certificates. Merging their seeds would answer a different OR question.