LeetCode #417 Medium

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.

Constraints
  • m == heights.length
  • n == heights[r].length
  • 1 <= m, n <= 200
  • 0 <= heights[r][c] <= 10⁵
bfsgridreverse-search
Open on LeetCode ↗
02

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.
How to spot this pattern

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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
▶3 rows, cols = len(heights), len(heights[0])
▶4 
▶5 def bfs(starts):
▶6 reach = [[False] * cols for _ in range(rows)]
▶7 for r, c in starts:
▶8 reach[r][c] = True
▶9 queue = deque(starts)
▶10 while queue:
▶11 r, c = queue.popleft()
▶12 for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
▶13 if (
▶14 0 <= nr < rows
▶15 and 0 <= nc < cols
▶16 and not reach[nr][nc]
▶17 and heights[nr][nc] >= heights[r][c]
▶18 ):
▶19 reach[nr][nc] = True
▶20 queue.append((nr, nc))
▶21 return reach
▶22 
▶23 pac_starts = [(r, 0) for r in range(rows)] + [(0, c) for c in range(1, cols)]
▶24 atl_starts = [(r, cols - 1) for r in range(rows)] + [(rows - 1, c) for c in range(cols - 1)]
▶25 pacific = bfs(pac_starts)
▶26 atlantic = bfs(atl_starts)
▶27 return [
▶28 [r, c]
▶29 for r in range(rows)
▶30 for c in range(cols)
▶31 if pacific[r][c] and atlantic[r][c]
▶32 ]
012012pacificatlantic122243331queue(0, 0)front(1, 0)(2, 0)(0, 1)(0, 2)5 Pacific shore cells queued
oceanPacifictop row + left column
reached5cells
Every cell on the top row or the left column drains straight into the Pacific, so all of them are marked and queued at once. From here the search climbs: it only steps to a neighbour at least as high, because water from that neighbour could flow back down to here.
012012pacificatlantic122243331queue(1, 0)front(2, 0)(0, 1)(0, 2)pop (0, 0): 0 new
pop(0, 0)height 1
reached5Pacific cells
queue4cells waiting
Pop (0, 0), height 1. Every neighbour inside the grid is already marked, so there is nothing new to check. This branch of the climb ends here.
012012pacificatlantic122243331queue(2, 0)front(0, 1)(0, 2)(1, 1)pop (1, 0): 1 new
pop(1, 0)height 2
reached6Pacific cells
queue4cells waiting
Pop (1, 0), height 2. (1, 1) has height 4 ≥ 2, so it joins.
012012pacificatlantic122243331queue(0, 1)front(0, 2)(1, 1)(2, 1)pop (2, 0): 1 new
pop(2, 0)height 3
reached7Pacific cells
queue4cells waiting
Pop (2, 0), height 3. (2, 1) has height 3, equal, so it joins.
012012pacificatlantic122243331queue(0, 2)front(1, 1)(2, 1)pop (0, 1): 0 new
pop(0, 1)height 2
reached7Pacific cells
queue3cells waiting
Pop (0, 1), height 2. Every neighbour inside the grid is already marked, so there is nothing new to check. This branch of the climb ends here.
012012pacificatlantic122243331queue(1, 1)front(2, 1)(1, 2)pop (0, 2): 1 new
pop(0, 2)height 2
reached8Pacific cells
queue3cells waiting
Pop (0, 2), height 2. (1, 2) has height 3 ≥ 2, so it joins.
012012pacificatlantic122243331queue(2, 1)front(1, 2)pop (1, 1): 0 new
pop(1, 1)height 4
reached8Pacific cells
queue2cells waiting
Pop (1, 1), height 4. Every neighbour inside the grid is already marked, so there is nothing new to check. This branch of the climb ends here.
012012pacificatlantic122243331queue(1, 2)frontpop (2, 1): 0 new
pop(2, 1)height 3
reached8Pacific cells
queue1cells waiting
Pop (2, 1), height 3. (2, 2) has height 1 < 3, so water there cannot flow up to here. This branch of the climb ends here.
012012pacificatlantic122243331queueemptypop (1, 2): 0 new
pop(1, 2)height 3
reached8Pacific cells
queue0cells waiting
Pop (1, 2), height 3. (2, 2) has height 1 < 3, so water there cannot flow up to here. This branch of the climb ends here. The queue is now empty: the Pacific search has marked all 8 cells that drain into the Pacific.
012012pacificatlantic122243331reached by pacificqueue(0, 2)front(1, 2)(2, 2)(2, 0)(2, 1)5 Atlantic shore cells queued
oceanAtlanticbottom row + right column
reached5cells
The Pacific search is over; its cells keep a blue dot. Now a fresh search starts from the bottom row and the right column, with its own marks, so the Pacific marks cannot block it.
012012pacificatlantic122243331reached by pacificqueue(1, 2)front(2, 2)(2, 0)(2, 1)(0, 1)pop (0, 2): 1 new
pop(0, 2)height 2
reached6Atlantic cells
queue5cells waiting
Pop (0, 2), height 2. (0, 1) has height 2, equal, so it joins.
012012pacificatlantic122243331reached by pacificqueue(2, 2)front(2, 0)(2, 1)(0, 1)(1, 1)pop (1, 2): 1 new
pop(1, 2)height 3
reached7Atlantic cells
queue5cells waiting
Pop (1, 2), height 3. (1, 1) has height 4 ≥ 3, so it joins.
012012pacificatlantic122243331reached by pacificqueue(2, 0)front(2, 1)(0, 1)(1, 1)pop (2, 2): 0 new
pop(2, 2)height 1
reached7Atlantic cells
queue4cells waiting
Pop (2, 2), height 1. Every neighbour inside the grid is already marked, so there is nothing new to check. This branch of the climb ends here.
012012pacificatlantic122243331reached by pacificqueue(2, 1)front(0, 1)(1, 1)pop (2, 0): 0 new
pop(2, 0)height 3
reached7Atlantic cells
queue3cells waiting
Pop (2, 0), height 3. (1, 0) has height 2 < 3, so water there cannot flow up to here. This branch of the climb ends here.
012012pacificatlantic122243331reached by pacificqueue(0, 1)front(1, 1)pop (2, 1): 0 new
pop(2, 1)height 3
reached7Atlantic cells
queue2cells waiting
Pop (2, 1), height 3. Every neighbour inside the grid is already marked, so there is nothing new to check. This branch of the climb ends here.
012012pacificatlantic122243331reached by pacificqueue(1, 1)frontpop (0, 1): 0 new
pop(0, 1)height 2
reached7Atlantic cells
queue1cells waiting
Pop (0, 1), height 2. (0, 0) has height 1 < 2, so water there cannot flow up to here. This branch of the climb ends here.
012012pacificatlantic122243331reached by pacificqueueemptypop (1, 1): 0 new
pop(1, 1)height 4
reached7Atlantic cells
queue0cells waiting
Pop (1, 1), height 4. (1, 0) has height 2 < 4, so water there cannot flow up to here. This branch of the climb ends here. The queue is now empty: the Atlantic search has marked all 7 cells that drain into the Atlantic.
012012pacificatlantic122243331queueemptyreturn 6 cells
answer6 cellsmarked by both searches
Keep the cells marked twice. (0, 1), (0, 2), (1, 1), (1, 2), (2, 0), (2, 1) drain to both oceans. (0, 0) reaches only the Pacific; (1, 0) reaches only the Pacific; (2, 2) reaches only the Atlantic, so they are left out. Each search touched each cell at most once, so the work is O(m · n).
05

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.

▶1class Solution:
▶2 def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
▶3 sys.setrecursionlimit(100000)
▶4 rows, cols = len(heights), len(heights[0])
▶5 pacific, atlantic = set(), set()
▶6 
▶7 def dfs(r, c, reach):
▶8 reach.add((r, c))
▶9 for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
▶10 if (
▶11 0 <= nr < rows
▶12 and 0 <= nc < cols
▶13 and (nr, nc) not in reach
▶14 and heights[nr][nc] >= heights[r][c]
▶15 ):
▶16 dfs(nr, nc, reach)
▶17 
▶18 for r in range(rows):
▶19 dfs(r, 0, pacific)
▶20 dfs(r, cols - 1, atlantic)
▶21 for c in range(cols):
▶22 dfs(0, c, pacific)
▶23 dfs(rows - 1, c, atlantic)
▶24 return [[r, c] for r, c in pacific & atlantic]
06

Common pitfalls

Keeping the downhill comparison while climbing

✗ Wrong
if heights[nr][nc] <= heights[r][c]:
✓ Right
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 >=

✗ Wrong
if heights[nr][nc] > heights[r][c]:
✓ Right
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.

07

Complexity

Time
O(m · n)
Space
O(m · n)
The BFS marks and pops each cell at most once per ocean and checks its 4 neighbours, so the two searches together cost O(m · n). The two marked grids and the queue take O(m · n) space.
08

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.