Pacific Atlantic Water Flow
LeetCode 417 · Medium · solution, intuition & step-by-step walkthrough
Reverse BFS from each ocean; intersect.
This is how I solved Pacific Atlantic Water Flow (LeetCode 417), a medium problem from the Graph Fundamentals / DFS-BFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Instead of testing every cell, flow water uphill from each ocean. BFS from the Pacific border into cells that are at least as high, then from the Atlantic border; cells reachable from both can drain to both oceans.
Approach
- 1
Pacific starts: top row and left column. Atlantic: bottom row and right column.
- 2
BFS into neighbours with height ≥ current.
- 3
Return cells in both reachable sets.
How I solved it
Two reverse BFSPythonO(m·n) time
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m = len(heights)
n = len(heights[0])
di = [0,+1,0,-1] #top,right,bottom,left
dj = [+1,0,-1,0] #top,right,bottom,left
pacific_q=deque([])
atlantic_q = deque([])
for i in range(m):
pacific_q.append((i,0))
atlantic_q.append((i,n-1))
for j in range(n):
pacific_q.append((0,j))
atlantic_q.append((m-1,j))
def bfs(q):
reachable = set()
while q:
srow,scol = q.popleft()
reachable.add((srow,scol))
for k in range(4):
nrow = srow+di[k]
ncol = scol+dj[k]
if 0<=nrow<m and 0<=ncol<n and heights[nrow][ncol]>=heights[srow][scol]:
if (nrow,ncol) not in reachable:
reachable.add((nrow,ncol))
q.append((nrow,ncol))
return reachable
pacific_reachable = bfs(pacific_q)
atlantic_reachable = bfs(atlantic_q)
return list(pacific_reachable.intersection(atlantic_reachable))
Pacific Atlantic Water Flow — FAQ
What is the intuition behind Pacific Atlantic Water Flow?
Instead of testing every cell, flow water uphill from each ocean. BFS from the Pacific border into cells that are at least as high, then from the Atlantic border; cells reachable from both can drain to both oceans.
How do you solve Pacific Atlantic Water Flow (LeetCode 417)?
1. Pacific starts: top row and left column. Atlantic: bottom row and right column. 2. BFS into neighbours with height ≥ current. 3. Return cells in both reachable sets.
What is the time and space complexity of Pacific Atlantic Water Flow?
Time: O(m · n). Space: O(m · n). (Accepted approach: Two reverse BFS.)
What are common mistakes in Pacific Atlantic Water Flow?
Water flows downhill, so the reverse search climbs uphill.