Reverse DFS from both oceans
Time O(rows × cols) Space O(rows × cols)DFS from Pacific border cells to neighbours with height ≥ current; same for the Atlantic; collect cells marked by both.
import java.util.*;
class Solution {
public List<List<Integer>> pacificAtlantic(int[][] heights) {
int m = heights.length, n = heights[0].length;
boolean[][] pac = new boolean[m][n], atl = new boolean[m][n];
for (int r = 0; r < m; r++) { climb(heights, r, 0, pac); climb(heights, r, n - 1, atl); }
for (int c = 0; c < n; c++) { climb(heights, 0, c, pac); climb(heights, m - 1, c, atl); }
List<List<Integer>> out = new ArrayList<>();
for (int r = 0; r < m; r++)
for (int c = 0; c < n; c++)
if (pac[r][c] && atl[r][c]) out.add(List.of(r, c));
return out;
}
private void climb(int[][] h, int r, int c, boolean[][] seen) {
if (seen[r][c]) return;
seen[r][c] = true;
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int[] d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr < 0 || nc < 0 || nr >= h.length || nc >= h[0].length) continue;
if (h[nr][nc] >= h[r][c]) climb(h, nr, nc, seen);
}
}
}Verdict: Each cell is visited at most twice.