Problem Description
Given an m x n matrix representing the height of each unit cell in a 2D elevation map, compute how much water can be trapped after it rains. Water is trapped in dips bounded by higher cells and cannot leak off the boundary.
Key Insights
- The problem is an extension of the trapping rain water problem from 1D to 2D.
- Use a min-heap (priority queue) to always process the lowest boundary cell.
- Start from the boundary and gradually work inward, updating water level based on the current minimum height.
- A cell can trap water if its height is less than the current water level; update the water level as max(current height, neighbor height).
- Use BFS to traverse neighbor cells to ensure all cells are considered only once.
Space and Time Complexity
Time Complexity: O(m * n * log(m * n)) because each cell is pushed and popped from the heap. Space Complexity: O(m * n) due to the heap and visited flags.
Solution
We solve the problem using a multi-source breadth-first search (BFS) that originates from all boundary cells. A min-heap keeps track of the current boundary, ensuring that we always examine the cell with the smallest height. For each extracted boundary cell, we check its neighbors: if a neighbor has not been visited, it can potentially trap water. The trapped water is computed as the difference between the current boundary height and the neighbor’s height (if positive). The neighbor is then updated to have an effective height equal to the maximum of its original height and the current boundary, and it is pushed to the heap. This approach prevents overlooking lower barriers inside the grid while ensuring we only compute trapped water for valid depressions.