Pacific Atlantic Water Flow
Find the cells whose rain can reach both oceans by climbing uphill from each ocean's edges.
The problem
You get a grid heights with the land height of every cell on an island. The Pacific Ocean touches the top and left edges, and the Atlantic Ocean touches the bottom and right edges. Rain flows from a cell to a neighbor above, below, left or right whose height is less than or equal to its own, and from an edge cell into the ocean beside it. Return [r, c] for every cell whose rain can reach both oceans, in any order.
Input heights = [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
Output [[0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
The 1 and the 2 in the top row can only drain into the Pacific. Every other cell has a downhill path to both: for example, 6 flows through 5, 4 and 3 to the top edge.
Input heights = [[3, 1, 2]]
Output [[0, 0], [0, 1], [0, 2]]
In a single row, every cell touches the top edge (Pacific) and the bottom edge (Atlantic).
Key constraint: The grid can be 200 by 200, so a separate downhill search from each of its 40,000 cells is too slow.
How to spot the pattern
- You must find every cell that can reach a target region (an ocean's edge) under a movement rule.
- Asking the question in reverse, from the targets outward, answers it for all cells in one search.
The idea
Testing every cell on its own means one search per cell. Turn it around: start at an ocean's edge cells and walk uphill, to neighbors that are at least as high, because water from those neighbors can flow down to where you stand. One such search from all Pacific edge cells marks every cell that drains into the Pacific, a second does the same for the Atlantic, and the answer is the cells marked by both.
Brute force: From every cell, search downhill and check whether the search touches both oceans, which costs O((m * n)^2) time.
Step by step
- 1Make two boolean grids,
pacificandatlantic. - 2Write
climb(r, c, seen), which returns if the cell is already marked, and otherwise marks it and climbs to every neighbor at least as high. - 3Call
climbwithpacificfrom every cell of the top row and the left column. - 4Call
climbwithatlanticfrom every cell of the bottom row and the right column. - 5Return every cell that is marked in both grids.
See the pattern move
The graph bfs and dfs pattern on a small example. Step through it, or press play.
Code
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
rows, cols = len(heights), len(heights[0])
pacific = [[False] * cols for _ in range(rows)]
atlantic = [[False] * cols for _ in range(rows)]
def climb(r: int, c: int, seen: List[List[bool]]) -> None:
# Marks every cell whose water can flow down to (r, c), by walking uphill.
if seen[r][c]:
return
seen[r][c] = True
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and heights[nr][nc] >= heights[r][c]:
climb(nr, nc, seen)
for r in range(rows):
climb(r, 0, pacific) # left edge
climb(r, cols - 1, atlantic) # right edge
for c in range(cols):
climb(0, c, pacific) # top edge
climb(rows - 1, c, atlantic) # bottom edge
return [[r, c] for r in range(rows) for c in range(cols) if pacific[r][c] and atlantic[r][c]]Complexity
Time
O(m * n)
Space
O(m * n)
Each cell is marked at most once per ocean; the two boolean grids and the recursion stack take O(m * n).
Watch out for
- Walking downhill from the edges: going from the ocean inward, you must move to neighbors that are higher or equal.
- Using a strict
>and missing flat stretches, where water flows between equal heights. - Forgetting that the top-right and bottom-left corners touch both oceans at once.
Follow-up questions
Can you do it with BFS instead of DFS?
Yes. Put all the edge cells of one ocean in a queue at once and expand uphill. It is a multi-source BFS and avoids deep recursion.
What if you had to say, for every cell, which oceans it reaches?
You already have it: the two grids tell you Pacific only, Atlantic only, both or neither for each cell.
In Hinglish
Har cell se neeche bahaane ke bajaye, ocean ke kinaron se upar chadho: padosi ki height barabar ya zyada ho tabhi jao. Jo cell dono oceans ki list mein aaye, wahi answer hai.