Pacific Atlantic Water Flow - Problem

There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.

The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).

The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.

Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.

Input & Output

Example 1 — Basic Island Grid
$ Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
💡 Note: These cells can flow water to both Pacific (top/left edges) and Atlantic (bottom/right edges). For example, cell (0,4) with height 5 can flow to Pacific through the top edge and to Atlantic through the right edge.
Example 2 — Simple Small Grid
$ Input: heights = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[0,2],[1,2],[2,0],[2,1],[2,2]]
💡 Note: Water flows from higher to lower or equal heights. Cell (0,2) can reach Pacific via top edge and Atlantic via right edge. Cell (2,0) can reach Pacific via left edge and Atlantic via bottom edge.
Example 3 — Single Cell
$ Input: heights = [[1]]
Output: [[0,0]]
💡 Note: A single cell borders both oceans (touches all edges), so water can flow to both Pacific and Atlantic oceans.

Constraints

  • m == heights.length
  • n == heights[r].length
  • 1 ≤ m, n ≤ 200
  • 0 ≤ heights[r][c] ≤ 105

Visualization

Tap to expand
Pacific Atlantic Water Flow Problem123456789PACIFICPACIFICATLANTICATLANTICWater Flow Rules:• Water flows from higher to equal/lower heights• Can move North, South, East, West• Pacific Ocean: Top and Left edges• Atlantic Ocean: Bottom and Right edgesReaches Both OceansGreen cells can flow to both Pacific and Atlantic!Output: [[0,2], [1,1], [2,0], [2,1], [2,2]]
Understanding the Visualization
1
Input Grid
Matrix of heights with Pacific (top/left) and Atlantic (bottom/right) boundaries
2
Flow Rules
Water flows to adjacent cells with equal or lower height
3
Output
Coordinates of cells that can reach both oceans
Key Takeaway
🎯 Key Insight: Instead of flowing down from each cell, flow up from ocean boundaries to find all reachable cells efficiently
Asked in
Google 32 Amazon 28 Microsoft 15 Facebook 12
85.6K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen