Maps app~30 min2s · 256 MBtarget O(r c) time, O(r c) spaceclassic twin: lc-417dfs
A mapping app stores the height of every square cell of a hillside, in whole metres. Rain that falls on a cell runs to a neighbour that shares a side and is not higher. It keeps running as long as such a neighbour exists.
The north and west edges of the map drain into the first river. The south and east edges drain into the second river. A cell on an edge can always send water to the rivers at its own edge. The planning team wants the cells whose rain can reach both rivers.
Write drain_to_both(heights).
heights[r][c] is the height of the cell in row r and column c.[row, column] pairs, in order of row and then column.Input: heights = [[3,3,4,5], [3,2,3,4], [2,4,5,3], [6,7,1,4]]
Output: [[0, 3], [2, 2], [3, 0], [3, 1]]The solution works backwards. It starts at the edge cells of one river. It climbs to side neighbours that are at least as high, because those are the cells whose water could arrive. The trace marks the cells that reach each river, with 1 for yes.
| First river | Second river |
|---|---|
| 1 1 1 1 | 0 0 0 1 |
| 1 0 0 0 | 0 0 0 1 |
| 1 1 1 0 | 0 0 1 1 |
| 1 1 0 0 | 1 1 1 1 |
The cells with a 1 in both tables are (0, 3), (2, 2), (3, 0) and (3, 1).
Input: heights = [[1, 1], [1, 1]]
Output: [[0, 0], [0, 1], [1, 0], [1, 1]]Water moves between cells of equal height, so every cell reaches both rivers.
Input: heights = [[5, 1], [6, 2]]
Output: [[0, 0], [0, 1], [1, 0], [1, 1]]Cell (1, 0) is on the west edge and on the south edge, so it reaches both rivers at once. The cell (0, 0) is also in the north row and runs down to (0, 1), which is in the last column.
1 ≤ heights.length ≤ 200 and 1 ≤ heights[r].length ≤ 200 (a rectangle)0 ≤ heights[r][c] ≤ 1,000,000A grid has up to 40,000 cells. Following the water forward from every cell costs up to 40,000 × 40,000 = 1.6 × 10^9 steps when the whole hillside is flat. Two flood fills from the edges visit each cell once each, so about 80,000 cell visits in all.