Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.
Example 1:
Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output: 4
Explanation: After the rain, water is trapped between the blocks.
We have two small ponds 1 and 3 units trapped.
The total volume of water trapped is 4.
The 1-D two-pointer argument does not extend to a matrix. Water escapes over the boundary, so a cell's water level is the lowest bottleneck on a path from the border.
Push every border height into a min-heap and grow inward. Pop the lowest wall \(h\); a shorter neighbor traps \(h-\textit{height}\) and re-enters with wall \(\max(h,\textit{height})\).
The heap always expands from the current lowest rim, so water levels never decrease and each cell is pushed once.
This is a variant of the trapping rain water problem. Since the heights on the matrix boundaries are fixed, we can add these boundary heights to a priority queue. Then, we repeatedly take out the minimum height from the priority queue and compare it with the heights of its four adjacent cells. If an adjacent cell's height is less than the current height, we can trap water there. The volume of trapped water is the difference between the current height and the adjacent height. We then add the larger height back to the priority queue and repeat this process until the priority queue is empty.
The time complexity is \(O(m \times n \times \log (m \times n))\), and the space complexity is \(O(m \times n)\), where \(m\) and \(n\) are the number of rows and columns in the matrix, respectively.