#417

Pacific Atlantic Water Flow

Medium Reverse BFS/DFS from the oceans

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Rain flows from a cell to neighbours with equal or lower height. The Pacific touches the top and left edges, the Atlantic the bottom and right. Return cells from which water can reach both oceans.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: cells from which water can reach both oceans.

Why this works: flip it: start from each ocean's edge and climb uphill. Cells reached from both oceans are the answer.

Example: a high peak in the middle of the grid

reachable uphill from the top/left edge and from the bottom/right edge → included

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using < instead of >= when climbing — equal heights also let water flow.

Solve on LeetCode ↗
Complexity
  • Time: O(m·n).
  • Space: O(m·n).
Topic: Graphs
🎬 Episodes 74–85: video coming soon