DSA AnimatorDSA animations
Pacific Atlantic Water Flow LC #417 Medium Graph · BFS · Reverse from Oceans
Problem

Grid with Pacific (top/left) and Atlantic (bottom/right). Water flows to equal/lower cells. Return cells that can reach both oceans.

Example
Input: heights = [[1,2,2,3,5],...]
Output: [[0,4],[1,3],[1,4],...]
Try Examples
Custom: rows separated by /
Approach
Reverse BFS from Oceans
BFS from Pacific borders (top+left) going uphill. BFS from Atlantic borders (bottom+right). Intersection = answer.
Grid — P=Pacific, A=Atlantic, ★=both
Load an example.
Variables
P count
—
A count
—
Both
—
Phase
—
Step Logic
Press ▶ Play or Next Step.
✓
Ready
0/0
Select example and Play.
Algorithm
1
BFS from Pacific borders (uphill)
2
BFS from Atlantic borders
3
Return cells with pac AND atl
Time
O(m·n)
Space
O(m·n)
Why Reverse

Instead of tracing water down, trace reachability up from oceans. Non-decreasing path from border → cell means water can flow border→cell.

How to solve Pacific Atlantic Water Flow

LeetCode 417 · Medium · Graph · Pattern: Reverse Multi-Source DFS

Why the obvious approach is slow

Starting a search from every single cell, and checking whether it reaches each ocean, repeats the same work again and again. That is O of the grid size squared.

The key idea

Turn the question around, and let water climb up from the oceans instead. From the Pacific edges, move to neighbours that are equal or higher, and mark everything you reach. Do the same from the Atlantic edges with a second marking. A cell reachable in both searches can drain into both oceans.

Remember

When many sources ask the same question, search backwards from the targets. Flowing down becomes climbing up.

Run the animation above on your own input, or watch the 1:54 video explanation of Pacific Atlantic Water Flow with a dry run and Java code.

More Graph problems