CodingNodes / Graphs / Pacific Atlantic Water Flow System design Space play · ←→ step · R restart

Problem

An island is a grid of heights. heights[r][c] is the height of one cell.

Water on a cell flows to any of its four neighbors (up, down, left, right) whose height is less than or equal to its own. Water on a cell on the island's edge can also flow straight into the ocean next to that edge. The Pacific touches the top row and the left column. The Atlantic touches the bottom row and the right column.

Return every cell [r, c] from which water can reach both oceans. The cells may be returned in any order.

Constraints

  • 1 ≤ rows, cols ≤ 200
  • 0 ≤ heights[r][c] ≤ 100000

Examples: pick one to animate

Solutions

TimeO(rows · cols) SpaceO(rows · cols)

Time: Each ocean's flood marks each cell True at most once, pushes it once and checks its 4 neighbors once. The final scan visits each cell once.

Space: The two True/False grids and the stack each hold up to rows · cols entries.

Asking "can this cell reach the ocean?" for every cell repeats work. Turn it around: start from the cells next to an ocean and walk uphill (to neighbors that are the same height or higher). Every cell reached this way can send its water down the same path to that ocean. Do it once for the Pacific and once for the Atlantic with a stack, then keep the cells that are True in both grids.