Pacific Atlantic Water Flow
Pacific Atlantic Water Flow is LeetCode 417 (Medium). An island is an m × n grid heights. The Pacific touches its top and left edges; the Atlantic touches its bottom and right edges.
Rain on a cell flows to a side neighbour (up, down, left or right) whose height is less than or equal to its own. A cell on an edge also flows straight into the ocean on that side.
Return every cell [r, c] from which water can reach both oceans, in any order.
m and n go up to 200, so the grid has up to 40,000 cells, and each cell should be visited only a few times.
- m == heights.length
- n == heights[r].length
- 1 <= m, n <= 200
- 0 <= heights[r][c] <= 10⁵
Intuition
Letting water run downhill from every cell repeats the same search over and over, up to O((m·n)²) work. Turn the question around and start from the oceans.
- Reverse the flow: water runs from cell A down to cell B exactly when you can climb from B to A, stepping only onto cells of equal or greater height. So the cells that drain into an ocean are the cells you can climb to from its shore.
- One search per ocean: one search from all Pacific edge cells marks everything that drains to the Pacific; a second does the same for the Atlantic.
- Intersect: a cell marked by both searches drains to both oceans.
When a grid question asks which cells can reach a border, or are cut off from one, search from the border inward instead of from every cell. Surrounded Regions (130) and Number of Enclaves (1020) use the same trick. This problem has two borders, so the search runs twice and the answer is the overlap.
Approach
Before reading on: in the first example, can water from the centre cell (height 4) reach the Atlantic? Then decide which way you would have to step if you started at the ocean instead. Aim for O(m·n).
Two ways to solve it
A queue climbs outward from every shore cell of one ocean at once.
- Time: each cell is popped at most once per ocean.
- Extra state: two marked grids and a queue.
- Depth: no recursion, so any grid shape is safe.
The safe default in every language.
A recursive call climbs from each shore cell as far as it can, then backs up.
- Time: the same cells are marked.
- Extra state: two sets plus the call stack.
- Depth: a winding path can need m · n = 40,000 nested calls.
Shorter code, and the version most tutorials show.
Both mark the same cells in O(m · n). The BFS has no recursion, so it cannot overflow the stack on a 200 × 200 grid; the steps, code and live demo follow it, and the DFS code is further down.
List the shore cells
The Pacific starts are the whole left column and the whole top row; the Atlantic starts are the whole right column and the whole bottom row. Use every edge cell, not only the corners, because each one drains straight into its ocean.
Climb from the shore with BFS
Mark all start cells and put them in a queue. Pop a cell and look at its four side neighbours. A neighbour joins when it is:
- inside the grid;
- not marked yet;
- at least as high as the popped cell.
Mark it and queue it. Marking on entry means no cell is queued twice.
Run it once per ocean
Call the BFS with the Pacific starts, then again with the Atlantic starts, each with its own marked grid. Sharing one grid would let the first search block the second, and the overlap would come out empty.
Keep the cells marked twice
Scan the grid and return every [r, c] that is marked in both grids. Those cells drain to the Pacific and to the Atlantic.
Code in Python, C++ and Java
DFS version
Call dfs on every shore cell with that ocean's set; each call adds its cell and recurses into every neighbour that is not in the set and at least as high. In Python, sys.setrecursionlimit lifts the default limit of 1000 calls.
Common pitfalls
Keeping the downhill comparison while climbing
if heights[nr][nc] <= heights[r][c]:
if heights[nr][nc] >= heights[r][c]:
The search runs backwards, from the ocean up to the cells that drain into it, so the neighbour must be at least as high as the current cell. The downhill test marks cells that water could never send to this ocean.
Using > instead of >=
if heights[nr][nc] > heights[r][c]:
if heights[nr][nc] >= heights[r][c]:
Water also flows between cells of equal height. The strict test stops at every flat stretch, so in the first example cell (2, 1), height 3 next to the shore cell (2, 0), also 3, is missed by the Pacific search.
Complexity
Pacific Atlantic Water Flow FAQ
Can water flow diagonally?
No. Water moves only up, down, left or right, so each cell has at most 4 neighbours and the search checks only those 4.
Does the order of the returned cells matter?
No. LeetCode accepts the cells in any order, so scanning the grid row by row, or intersecting two sets, are both fine.