26 / 75
Find cells that can flow to both oceans by doing reverse DFS from ocean borders.
Example:
Input:
heights=[[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]Output:
[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]Common Mistakes:
- Trying to DFS from each cell to both oceans (too slow - O(m²n²))
- Not doing reverse DFS (from oceans inward with increasing/equal heights)
- Forgetting to check >= instead of > for equal height flow
- Missing corner cells that touch both oceans
Notes:
Key insight: reverse the problem - flow FROM oceans TO cells. Time O(m*n), Space O(m*n). Much better than forward approach.
💻
Java Solution Hidden
Enable “Show Full Solution” to view the code
Find cells that can flow to both oceans by doing reverse DFS from ocean borders.
Example:
Input:
heights=[[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]Output:
[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]Common Mistakes:
- Trying to DFS from each cell to both oceans (too slow - O(m²n²))
- Not doing reverse DFS (from oceans inward with increasing/equal heights)
- Forgetting to check >= instead of > for equal height flow
- Missing corner cells that touch both oceans
Notes:
Key insight: reverse the problem - flow FROM oceans TO cells. Time O(m*n), Space O(m*n). Much better than forward approach.
26/75
Pacific Atlantic Water Flow