MEDIUM NC#83 Blind #29 Graphs / DFS
417. Pacific Atlantic Water Flow
๐ Problem
There is an m x n rectangular island that borders both the Pacific and Atlantic oceans. The Pacific Ocean touches the left and top edges of the island, and the Atlantic Ocean touches the right and bottom edges of the island. Return a 2D list of grid coordinates result[i] such that result[i].length = 2, and result[i][0] lists all coordinates (r, c) of cells where rain water can flow to both the Pacific and Atlantic oceans.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขRecursive stack flow
- โขCycle prevention
- โขPost-order reasoning
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply DFS reasoning pattern
๐ก Approach
- โ For Pacific: flow to top and left edges
- โ For Atlantic: flow to bottom and right edges
- โ Use DFS from each border cell
- โ Track cells that can reach each ocean
- โ Time: O(m * n), Space: O(m * n)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขFor Pacific: flow to top and left edges
- โขFor Atlantic: flow to bottom and right edges
- โขUse DFS from each border cell
Common Pitfalls
- โขTrack cells that can reach each ocean
- โขTime: O(m * n), Space: O(m * n)
๐งช Test Cases
Test Case 1
Not run Input:
pacificAtlantic(heights: number[][]); Expected:
Computed from hidden reference Test Case 2
Not run Input:
pacificAtlantic([[1,2,2,3,4],[3,2,2,3,0,1],[2,3,1,2,4,1,5],[3,2,2,3,0,0,3,2,4,1]]); Expected:
Computed from hidden reference Test Case 3
Not run Input:
pacificAtlantic([[2,1],[2,2,1],[3,2,4,1],[3,2,2,4,1,3,2,4,1]]); Expected:
Computed from hidden reference ๐ Code Editor
๐ค Output