Approach
Depth-first search
For Pacific Atlantic Water Flow, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 32 lines of Python from the credited upstream file 417-2.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def pacificAtlantic(self, heights: list[list[int]]) -> list[list[int]]:3 m = len(heights)4 n = len(heights[0])5 seenP = [[False] * n for _ in range(m)]6 seenA = [[False] * n for _ in range(m)]7 8 def dfs(i: int, j: int, h: int, seen: list[list[bool]]) -> None:9 if i < 0 or i == m or j < 0 or j == n:10 return11 if seen[i][j] or heights[i][j] < h:12 return13 14 seen[i][j] = True15 dfs(i + 1, j, heights[i][j], seen)16 dfs(i - 1, j, heights[i][j], seen)17 dfs(i, j + 1, heights[i][j], seen)18 dfs(i, j - 1, heights[i][j], seen)19 20 for i in range(m):21 dfs(i, 0, 0, seenP)22 dfs(i, n - 1, 0, seenA)23 24 for j in range(n):25 dfs(0, j, 0, seenP)26 dfs(m - 1, j, 0, seenA)27 28 return [[i, j]29 for i in range(m)30 for j in range(n)31 if seenP[i][j] and seenA[i][j]]32