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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit