← Visualizers
Graphs · Multi-source flood, reversed LeetCode 417

Pacific Atlantic Water Flow / visualized

Asked forwards — from this cell, can water reach both oceans? — every cell needs its own traversal: O((mn)²). Asked backwards — which cells can each ocean reach if water flowed uphill? — it is one flood from the Pacific border, one from the Atlantic border, and the answer is the intersection. Going uphill the test is h[next] >= h[cur]; the toggle flips it, which is the bug everyone writes once.

Execution

idle
Pacific
Pacific
Atlantic
Atlantic
Press Run to begin.
0 / 0
Speed

Java · running line

Pacific reaches it Atlantic reaches it both — in the answer waiting in the queue neither ocean
O(m·n) time, O(m·n) space  ·  two floods instead of mn of them. Answers are returned sorted by row, then column. Walking out from the ocean is walking against the water, so the comparison inverts: h[next] >= h[cur]. Writing <= there is the same traversal running the wrong way down the map.