Introduction
Pacific Atlantic Water Flow is one of the most important Matrix DFS and BFS interview problems.
You are given:
heights[][]Goal:
Find cells from which water can reach both oceans.Rules:
Pacific → Top + LeftAtlantic → Bottom + RightWater flows:
Higher → Lower or EqualExample
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]]Key Observation
Instead of starting from:
Every CellStart from:
Ocean Boundaries Run DFS/BFS from:
Pacific Border and Atlantic Border Then find:
IntersectionAlgorithm
1. Traverse Pacific borders.2. Traverse Atlantic borders.
3. Mark reachable cells.
4. Find common cells.
5. Return answer.
Dry Run
Pacific Reachable:
Top + Left Atlantic Reachable:
Top + LeftAnswer:
Cells present in both sets.Approach : DFS
Explanation
- Start from ocean borders.
- Move to greater or equal heights.
- Mark visited cells.
- Find intersection.