Given an m x n integer matrix height_map representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.
Function Signature
def trap_rain_water(height_map: list[list[int]]) -> int:
...
Rules
-
Water moves only between cells that share an edge (up, down, left, right). Touching at a corner is not a passage.
-
Water that reaches the outer boundary of the map spills off, so boundary cells never hold water.
-
Each unit of water depth over one cell counts as one unit of volume.
-
Coordinates in the examples are
(row, col)
, zero-indexed.
Constraints
-
m == len(height_map)
-
n == len(height_map[i])
-
1 <= m, n <= 200
-
0 <= height_map[i][j] <= 2 * 10^4
Examples
Input: height_map = [[1,4,3,1,3,2],
[3,2,1,3,2,4],
[2,3,3,2,3,1]]
Output: 4
Only the middle row's inner cells can hold water. Cells (1,1) and (1,2) form one pocket whose lowest surrounding wall is 3, so they hold 1 and 2 units; cell (1,4) with height 2 is also walled in at 3 and holds 1 unit; cell (1,3) has height 3 and holds nothing. Total 1 + 2 + 1 = 4.
Input: height_map = [[3,3,3,3,3],
[3,2,2,2,3],
[3,2,1,2,3],
[3,2,2,2,3],
[3,3,3,3,3]]
Output: 10
Every boundary cell has height 3, so the water level inside is 3. The 8 interior cells of height 2 hold 1 unit each and the center cell of height 1 holds 2 units, for 8 + 2 = 10.
Input: height_map = [[5,5,5,5],
[5,1,1,5],
[5,1,5,5],
[5,2,5,5]]
Output: 3
The three cells of height 1 at (1,1), (1,2) and (2,1) are connected, and the pocket touches the boundary cell (3,1) of height 2. Water above level 2 drains out through that cell, so each of the three cells holds 2 - 1 = 1 unit and cell (2,2) holds nothing.