Trapping Rain Water II

Given an `m x n` integer matrix `heightMap` where each cell holds the height of a unit block in a 2D elevation map, return *the total volume of water it can trap after raining*. Water on a cell can rise only as high as the lowest wall along some path that leads off the edge of the map. Cells on the border can never hold water.

30:00

Trapping Rain Water II
hard
Free written solution
Topics
Companies

Given an m x n integer matrix heightMap where each cell holds the height of a unit block in a 2D elevation map, return the total volume of water it can trap after raining.

Water on a cell can rise only as high as the lowest wall along some path that leads off the edge of the map. Cells on the border can never hold water.

Example 1:
Input: {"heightMap":[[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]}
Output: 4
Constraints:
  • m==heightMap.lengthm == \text{heightMap.length}

  • n==heightMap[i].lengthn == \text{heightMap}[i].\text{length}

  • 1≤m,n≤2001 \leq m, n \leq 200

  • 0≤heightMap[i][j]≤2⋅1040 \leq \text{heightMap}[i][j] \leq 2 \cdot 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"heightMap":[[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]}

A 3 x 6 height map. Water escapes over the edge, so the border cells form the first wall around the inside.

min-heap of walls (0):

empty

1
4
3
1
3
2
3
2
1
3
2
4
2
3
3
2
3
1

wall level

-

visited

0/18

water

0

wall frontier (in heap)
lowest wall, just popped
neighbor being filled
trapped water
Variables
VariableValue
cell-
level-
neighbor-
heap0
water0
DepthFunction Call
Stack empty
0/24