Pacific Atlantic Water Flow

MediumGraphs

An island is cut into an m × n grid of cells, and heights[r][c] is the height of the cell in row r, column c, with row 0 at the top. The Pacific Ocean washes the top and left edges of the island; the Atlantic washes the bottom and right edges.

Rain on a cell runs to a neighboring cell (up, down, left or right) whenever that neighbor is no higher than the cell it leaves, and a cell on an edge drains straight into the ocean along that edge.

Return the [row, column] of every cell whose rain can reach both oceans. The cells can come back in any order.

Examples

Example 1
Input:  heights = [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
Output: [[0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

The 1 and the 2 in the top left are lower than everything around them except the Pacific, so their rain never reaches the Atlantic. Every other cell drains both ways.

Example 2
Input:  heights = [[4]]
Output: [[0, 0]]

One cell touches all four edges, so it drains into both oceans.

Constraints

  • 1 ≤ m, n ≤ 200
  • 0 ≤ heights[r][c] ≤ 10⁵

Stuck?

Hint 1

Following the rain downhill from every cell repeats a lot of work. Turn it around: start at each ocean’s edge and walk uphill to find every cell that drains into it.

Hint 2

Run one DFS or BFS from all the Pacific edge cells and one from all the Atlantic edge cells, stepping only to a neighbor at least as high. The answer is the cells both walks reach.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur