← Back to DSA Animator
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.