iq.lab
Python starts when a code cell comes near or you run one
mediumDepth-first search target 25 min

Water to both oceans

heights is a grid of land, and heights[r][c] is the height of the cell in row r and column c. Two oceans wash against the grid: the Pacific along the top and left edges, the Atlantic along the bottom and right edges.

Rain falls on every cell. Water on a cell can flow to a neighbor (up, down, left or right) whose height is the same or lower, and it keeps flowing from there. A cell on an ocean's edge drains into that ocean. Water can split, so one cell can drain into both oceans.

Return every cell whose water can reach both oceans, each once, as a list of [row, col] pairs in any order.

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

Every cell except the 1 and the 2 in the top row. Apart from each other, every neighbor of theirs is higher, so their water stays on the top edge and reaches only the Pacific.

Example 2
Inputheights = [[3, 3, 3], [3, 1, 3], [3, 3, 3]]Output[[0, 0], [0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1], [2, 2]]

The 1 in the middle is a pit: every neighbor is higher, so its water goes nowhere. The ring of 3s can flow along equal heights to any edge.

Example 3
Inputheights = [[4, 2, 7]]Output[[0, 0], [0, 1], [0, 2]]

A single row touches the top edge and the bottom edge, so every cell drains into both oceans.

Constraints
  • 1 ≤ number of rows, number of columns ≤ 200

  • 0 ≤ heights[r][c] ≤ 105

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.