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
- 40 lines of Java from the credited upstream file 417-2.java.
- The implementation visibly relies on sequence storage.
- 4 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 public List<List<Integer>> pacificAtlantic(int[][] heights) {3 final int m = heights.length;4 final int n = heights[0].length;5 List<List<Integer>> ans = new ArrayList<>();6 boolean[][] seenP = new boolean[m][n];7 boolean[][] seenA = new boolean[m][n];8 9 for (int i = 0; i < m; ++i) {10 dfs(heights, i, 0, 0, seenP);11 dfs(heights, i, n - 1, 0, seenA);12 }13 14 for (int j = 0; j < n; ++j) {15 dfs(heights, 0, j, 0, seenP);16 dfs(heights, m - 1, j, 0, seenA);17 }18 19 for (int i = 0; i < m; ++i)20 for (int j = 0; j < n; ++j)21 if (seenP[i][j] && seenA[i][j])22 ans.add(new ArrayList<>(List.of(i, j)));23 24 return ans;25 }26 27 private void dfs(final int[][] heights, int i, int j, int h, boolean[][] seen) {28 if (i < 0 || i == heights.length || j < 0 || j == heights[0].length)29 return;30 if (seen[i][j] || heights[i][j] < h)31 return;32 33 seen[i][j] = true;34 dfs(heights, i + 1, j, heights[i][j], seen);35 dfs(heights, i - 1, j, heights[i][j], seen);36 dfs(heights, i, j + 1, heights[i][j], seen);37 dfs(heights, i, j - 1, heights[i][j], seen);38 }39}40