Rain That Reaches Both Coasts

Medium · Graphs, BFS & DFS · about 25 min

An island is a grid of land heights. The north edge (top row) and the west edge (left column) touch a lake. The south edge (bottom row) and the east edge (right column) touch the sea.

Rain that falls on a cell can flow to a neighbouring cell up, down, left or right whose height is less than or equal to the current cell's height. Water on a top-row or left-column cell can flow into the lake, and water on a bottom-row or right-column cell can flow into the sea.

Return every cell [row, col] from which rain can reach both the lake and the sea, sorted by row and then by column. An empty grid gives [].

Example:

cells_reaching_both([[1, 3, 2], [2, 4, 3], [5, 1, 1]]) → [[0, 1], [0, 2], [1, 1], [1, 2], [2, 0]]

Hints

  • Think backwards: which cells can the lake 'climb up' to? From a coast cell, you may step to a neighbour that is the same height or higher.
  • Run one search from every top-row and left-column cell, and another from every bottom-row and right-column cell. Keep two separate visited grids.
  • Collect the cells that are in both visited grids by looping rows, then columns, so the order comes out sorted.

Learn the pattern first: the Graphs, BFS & DFS lesson.

More Graphs, BFS & DFS problems