Problem 573527 · hard · Phase 05 Advanced Algorithms & Graphs

Rain That Reaches Both Rivers

grids · BFS · multi-source · reverse search

heights is a grid of land heights. A river runs along the north-west edge (next to the top row and the left column) and another along the south-east edge (next to the bottom row and the right column). Rain on a cell flows to any side-adjacent cell whose height is less than or equal to its own, and from any cell on the top row or left column it can spill into the north-west river (likewise bottom row / right column for the south-east river).

Return the list of cells [r, c] from which rain can reach both rivers, in row-major order (sorted by row, then column).

Examples

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]]
Explanation: (0,0) and (0,1) touch only the north-west river: rain there cannot
climb to a higher neighbour, and every path away from them goes uphill first.
(1,0) = 8 lies on the left column and also drains 8 -> 7 onto the bottom row.

Input:  heights = [[5]]
Output: [[0,0]]

Constraints

  • 1 <= rows, cols <= 60, 0 <= heights[r][c] <= 10**5
  • Target O(rows * cols) time.

Goals

  • Reverse the direction of a flow relation to search from the targets
  • Run one multi-source search per river and intersect the results
  • Return the answer cells in a deterministic order
Starting Python…