#1 Trapping Rain Water 3D HARD
Hard
Array
Heap
BFS
Given an m x n matrix of positive integers representing the height of each unit cell in a 3D elevation map, compute the volume of water it is able to trap after raining. Water can only flow in four directions (up, down, left, right) to boundary cells.
Example:
Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output: 4
Explanation: After rain, water is trapped between the blocks. We have two small ponds (1 index unit and 3 index units) trapped.
Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output: 4
Explanation: After rain, water is trapped between the blocks. We have two small ponds (1 index unit and 3 index units) trapped.
Time: O(mn log(mn))
Space: O(mn)
Test Cases: 8
Acceptance: 32%
Time Complexity
Space Complexity
Python Editor
Output
# Problem #1: Trapping Rain Water 3D
# Click "Run Code" to test your solution
# Output will appear here after execution
Solution Approach
Optimal Approach: Heap + BFS
This problem requires a heap to simulate the process of water trapping from boundaries to inner cells. The key insight is that the water height at each cell is determined by the minimum height of its boundary.
- Add all boundary cells to a min-heap
- Process cells in increasing height order
- For each cell, update the max boundary height
- For unvisited neighbors, calculate trapped water
- Add neighbors to the heap for processing
Complexity Analysis
Time Complexity: O(mn log(mn)) - Each cell is processed once, and heap operations take log time
Space Complexity: O(mn) - For storing visited cells and the heap
Learning Progress:
0%