Which cells drain to both oceans? Flip the flow: flood uphill from each coastline, then keep the cells both tides reach.
▼The problem
An m × n grid of heights is an island. The Pacific touches its top and left edges, the Atlantic its bottom and right edges. Rain flows from a cell to any neighbour of equal or lower height (and off the grid into the ocean from an edge cell). Return every cell whose water can reach both oceans.
Example (the LeetCode one):
[[1,2,2,3,5], [3,2,3,4,4], [2,4,5,3,1], [6,7,1,4,5], [5,1,1,2,4]]TRY IT ON LEETCODE ▶
The solution
def pacific_atlantic(heights):
rows, cols = len(heights), len(heights[0])
pac, atl = set(), set()
def climb(r, c, seen): # flood uphill
seen.add((r, c))
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 (nr, nc) not in seen
and heights[nr][nc] >= heights[r][c]):
climb(nr, nc, seen)
for r in range(rows):
climb(r, 0, pac); climb(r, cols - 1, atl)
for c in range(cols):
climb(0, c, pac); climb(rows - 1, c, atl)
return [[r, c] for r, c in pac & atl]Transcript
Pacific Atlantic Water Flow. An island is a grid of heights. The Pacific Ocean touches its top and left edges. The Atlantic touches its bottom and right edges.
When rain falls on a cell, it flows to any neighbor that is equal or lower, never uphill. Drop rain on this five in the middle. It can run down to the Pacific, and down to the Atlantic as well. Find every cell whose water can reach both oceans. On this island, there are seven.
The obvious plan is to drop rain on every cell, one at a time, and follow it downhill. That's twenty-five separate searches, and each one can wander over the whole island. Here they touch one hundred thirty-nine cells in total. On a big grid, that's m times n searches of up to m times n cells each: m times n, squared.
So flip it around. Instead of following water down to the sea, let the sea climb up the land. The Pacific starts on its edge and floods uphill, into any neighbor that is equal or higher. Every cell the tide reaches can drain back down to the Pacific. Then do the same from the Atlantic. The answer is wherever the two tides overlap.
In code, a helper adds a cell to a seen set, then climbs into every unseen neighbor that is at least as high. Call it from every edge cell of each ocean, and return the cells that are in both sets.
Let's run it. The Pacific fills its nine edge cells, climbs five more, then two: sixteen cells. The Atlantic fills its nine, climbs six more, then one: sixteen too. Seven cells are wet from both sides: the answer.
Each tide visits a cell at most once, so the work is m times n: thirty-two visits here, instead of one hundred thirty-nine. The two seen sets take m times n space.
Don't chase the water down. Let the oceans climb up. That's Pacific Atlantic Water Flow.