Pacific Atlantic Water Flow

35 min · pacificAtlantic()

A raindrop lands on a mountain map with two coastlines below it. Some peaks can drain to either coast; valleys may trap the drop on only one side.

You're given a rectangular matrix heights. Water may move from a cell to its top, bottom, left, or right neighbor only when that neighbor's height is equal or lower.

The Pacific touches the top and left edges. The Atlantic touches the bottom and right edges. Return every coordinate [row, col] whose water can reach both oceans.

A few ground rules:

  • A cell on an ocean's edge already reaches that ocean.
  • Water may cross a flat stretch because equal heights are allowed.
  • The coordinates may appear in any order, but each coordinate itself is always [row, col].

Constraints

  • 1 <= heights.length <= 200
  • 1 <= heights[r].length <= 200
  • Every row has the same length.
  • 0 <= heights[r][c] <= 1_000_000

Hints

Notice the repeated work

A search from every cell keeps walking through the same slopes. Try starting from an ocean instead—but decide what movement rule must reverse too.

Make water run uphill

In a reverse search, move from a cell to neighbors of equal or greater height. Any cell reached this way has a downhill path back to that ocean.

Two reachability maps

Search once from all Pacific edges and once from all Atlantic edges. A coordinate belongs in the answer exactly when both searches reach it.

Follow-up

How would your approach change if water could also move diagonally to an equal-or-lower neighbor?

Visible cases

Examples

Example 1

ready
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
  ]
]
Expected
[
  [
    0,
    4
  ],
  [
    1,
    3
  ],
  [
    1,
    4
  ],
  [
    2,
    2
  ],
  [
    3,
    0
  ],
  [
    3,
    1
  ],
  [
    4,
    0
  ]
]
Why
these seven cells each have a non-increasing route to both oceans

Example 2

ready
Input
heights = [
  [
    1,
    2
  ],
  [
    4,
    3
  ]
]
Expected
[
  [
    0,
    1
  ],
  [
    1,
    0
  ],
  [
    1,
    1
  ]
]
Why
three cells reach both edges; the height-1 corner can't climb out

Example 3

ready
Input
heights = [
  [
    1,
    2,
    1
  ],
  [
    2,
    9,
    2
  ],
  [
    1,
    2,
    1
  ]
]
Expected
[
  [
    0,
    1
  ],
  [
    0,
    2
  ],
  [
    1,
    0
  ],
  [
    1,
    1
  ],
  [
    1,
    2
  ],
  [
    2,
    0
  ],
  [
    2,
    1
  ]
]
Why
the peak and connecting ridge drain both ways, but two low corners don't

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite