Pacific Atlantic Water Flow
Master this topic with zero to advance depth.
Pacific Atlantic Water Flow
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
Water can flow to a neighboring cell (north, south, east, west) if the neighboring cell's height is less than or equal to the current cell's height.
Return a list of grid coordinates where rain water can flow to both the Pacific and Atlantic oceans.
Visual Representation
Pacific Ocean
| 1 2 2 3 2 |
| 3 2 3 4 4 |
| 2 4 5 3 1 | Atlantic Ocean
| 6 7 1 4 5 |
| 5 1 1 2 4 |Examples
Cells at these coordinates can flow to both oceans.
Level I: Brute Force (DFS from Every Cell)
Intuition
For every single cell in the grid, we start a traversal (DFS) to see if we can reach both the Pacific and Atlantic oceans. A cell can reach an ocean if there is a path of decreasing or equal heights to the boundary.
Thought Process
- For each cell
(r, c):- Run
canReachPacific(r, c)using DFS. - Run
canReachAtlantic(r, c)using DFS. - If both are true, add
(r, c)to results.
- Run
Why it's inefficient
We repeat the same exploration many times for neighboring cells. Many paths are re-calculated.
Detailed Dry Run
Grid: [[1, 2], [1, 1]]
| Cell | Reach Pac? | Reach Atl? | Result |
|---|---|---|---|
| (0,0) | Yes (Edge) | No (Trapped) | No |
| (0,1) | Yes (Edge) | Yes (Edge) | YES |
Level III: Optimal (DFS from Ocean Coasts)
Intuition
Instead of asking "Can this cell reach the ocean?", we ask "What cells can the ocean reach?". Water flows from high to low, so if we start at the ocean and go uphill (height >= current), we can find all reachable cells efficiently.
Thought Process
- Create two boolean grids:
canReachPacificandcanReachAtlantic. - Start DFS from all Pacific boundary cells (left and top edges) and mark reachable uphill cells in
canReachPacific. - Start DFS from all Atlantic boundary cells (right and bottom edges) and mark reachable uphill cells in
canReachAtlantic. - Cells marked in both grids are the result.
Pattern: Inverse Search / Multi-Source DFS
Detailed Dry Run
Grid: [[1,2],[1,1]]
| Ocean | Start Cells | Reachable (Uphill) |
|---|---|---|
| Pacific | (0,0),(0,1),(1,0) | (0,0), (0,1), (1,0) |
| Atlantic | (1,1),(0,1),(1,0) | (1,1), (0,1), (1,0) |
| Intersection: (0,1), (1,0), (1,1) |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.