Data Structures & Algorithms Graphs — BFS & DFS
💡
Exercise 112

Pacific Atlantic Water 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Water flows from higher to lower/equal cells. Pacific touches top & left, Atlantic touches bottom & right. Find cells that can reach both oceans.

Key insight: reverse the flow. Start from ocean borders and DFS inward to cells with height >= current. Intersection of both sets = answer.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Find how many cells can reach both oceans. Print the count.
Two DFS passes: from Pacific border, from Atlantic border. Use two visited sets. Answer = len(intersection).
🧪 Test Cases
Input
pacificAtlantic(heights)
Expected
7
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.