Pacific Atlantic Water Flow

Medium#417grid

You get a grid of heights, an island between two oceans: the Pacific washes its top and left edges, the Atlantic its bottom and right ones. Rain runs from a cell to a side neighbour that is no higher, and from an edge cell into the ocean there. List the cells whose water can reach both oceans. Our heights: 1 2 3, 4 5 2, 3 1 1 — the answer is 4 cells: (0, 2), (1, 0), (1, 1) and (2, 0).

input
heights: an m × n island, heights[r][c] the height of cell (r, c). The Pacific washes its top and left edges, the Atlantic its bottom and right ones.
returns
Every cell [r, c] whose rain can reach both oceans, in any order. Rain runs from a cell to a neighbour up, down, left or right that is no higher, and from an edge cell into the ocean there.
constraints
  • m = heights.length, n = heights[r].length, 1 ≤ m, n ≤ 25
  • 0 ≤ heights[r][c] ≤ 10⁵
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} heights
 * @return {number[][]}
 */
function pacificAtlantic(heights) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.