Pacific Atlantic Water Flow Problem
Description
LeetCode Problem 417.
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return a 2D list of grid coordinates result where result[i] = [r_i, c_i] denotes that rain water can flow from cell (r_i, c_i) to both the Pacific and Atlantic oceans.
Example 1:
Input: heights = [[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]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Example 2:
Input: heights = [[2,1],[1,2]]
Output: [[0,0],[0,1],[1,0],[1,1]]
Constraints:
- m == heights.length
- n == heights[r].length
- 1 <= m, n <= 200
- 0 <= heights[r][c] <= 10^5
Solution
Approach: BFS Uphill from Each Ocean
Simulating the rain from every cell repeats the same search many times, up to O((m · n)2) work. Turn the question around: instead of asking where water from a cell can go, ask which cells can send water to a given ocean.
Water flows from a cell to a neighbor that is lower or equal. So, walking backwards from the ocean, we may step from a cell to a neighbor that is higher or equal. Every cell reached that way can drain into that ocean.
- Start a BFS from all cells touching the Pacific (top row and left column) and mark every cell it reaches by only climbing (
heights[next] >= heights[current]). - Do the same from all cells touching the Atlantic (bottom row and right column).
- The answer is every cell marked by both searches.
Each search visits every cell at most once, because a cell is marked when it enters the queue and never added again. The comparison is the easy part to flip by mistake: since we walk against the flow, the neighbor must be at least as high as the current cell, not lower. Equal heights count too: water flows across a flat area.
A BFS with an explicit queue also avoids deep recursion: a 200 × 200 grid can have a climbing path through all 40,000 cells.
Complexity: O(m · n) time and O(m · n) space, where m and n are the number of rows and columns.
import collections
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
rows, cols = len(heights), len(heights[0])
def reaches(starts):
"""Cells whose water can flow to one of the start cells: a BFS that only climbs."""
seen = [[False] * cols for _ in range(rows)]
queue = collections.deque()
for r, c in starts:
if not seen[r][c]:
seen[r][c] = True
queue.append((r, c))
while queue:
r, c = queue.popleft()
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 not seen[nr][nc]
and heights[nr][nc] >= heights[r][c]): # water can flow from (nr, nc) down to (r, c)
seen[nr][nc] = True
queue.append((nr, nc))
return seen
# Pacific: top row and left column. Atlantic: bottom row and right column.
pacific = reaches([(0, c) for c in range(cols)] + [(r, 0) for r in range(rows)])
atlantic = reaches([(rows - 1, c) for c in range(cols)] + [(r, cols - 1) for r in range(rows)])
return [[r, c] for r in range(rows) for c in range(cols) if pacific[r][c] and atlantic[r][c]]
Now write it from memory
Close the write-up and solve it yourself against the tests.