Asked forwards — from this cell, can water reach both oceans? — every cell
needs its own traversal: O((mn)²). Asked backwards — which cells can
each ocean reach if water flowed uphill? — it is one flood from Pacific,
one flood from Atlantic, and the answer is the intersection.
"Simulating water flowing downhill from each interior cell forces us to restart traversal from scratch for each cell, resulting in $O((m \cdot n)^2)$ time."
"Instead, think: where could the water have come from? Start at ocean edges and flood uphill. The neighbor condition inverts: step to (nr, nc) only if heights[nr][nc] ≥ heights[r][c]."
"Run one multi-source BFS/DFS seeded with Pacific borders (top row + left column) into boolean[][] pac, and a second seeded with Atlantic borders (bottom row + right column) into boolean[][] atl."
"Any coordinate where pac[r][c] && atl[r][c] can drain to both oceans. Time is strictly $O(m \cdot n)$ and auxiliary space is $O(m \cdot n)$."
mn of them. Answers are returned sorted by row, then column. Walking out from the ocean is walking against the water, so the comparison inverts: h[next] >= h[cur].