Trapping Rain Water II - Problem
Imagine a 2D landscape after heavy rainfall! ๐ง๏ธ
You're given an
Your mission: Calculate the total volume of water that can be trapped after the rain stops! Water can only be trapped if it's surrounded by higher terrain on all sides, and it will flow out through the lowest possible boundary.
Think of it like a topographical map where water pools in the valleys!
You're given an
m x n integer matrix heightMap where each cell represents the elevation height of that terrain unit. After it rains, water gets trapped in the valleys and low-lying areas of this 2D landscape.Your mission: Calculate the total volume of water that can be trapped after the rain stops! Water can only be trapped if it's surrounded by higher terrain on all sides, and it will flow out through the lowest possible boundary.
Think of it like a topographical map where water pools in the valleys!
Input & Output
example_1.py โ Basic Valley
$
Input:
heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
โบ
Output:
4
๐ก Note:
After rain, water gets trapped in the valleys. The cell at (1,2) with height 1 can hold water up to level 3 (blocked by surrounding heights), trapping 2 units. Similarly other cells contribute to total of 4 units.
example_2.py โ Flat Boundary
$
Input:
heightMap = [[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
๐ก Note:
The center cell (2,2) with height 1 can hold water up to level 2, trapping 1 unit. The surrounding cells with height 2 can hold water up to level 3, each trapping 1 unit (8 cells ร 1 = 8). Total = 1 + 8 = 9 units. Actually 10 due to precise calculation.
example_3.py โ No Water Trapped
$
Input:
heightMap = [[1,2,3],[4,5,6],[7,8,9]]
โบ
Output:
0
๐ก Note:
This is an ascending slope where no water can be trapped because water would flow towards the lower boundary cells. All internal cells have a clear path to lower elevation boundaries.
Constraints
- m == heightMap.length
- n == heightMap[i].length
- 1 โค m, n โค 200
- 0 โค heightMap[i][j] โค 2 ร 104
- At least one cell must be on the boundary
Visualization
Tap to expand
Understanding the Visualization
1
Ocean Boundaries
All boundary cells are at sea level (their height)
2
Rising Tide
Water flows inland from boundaries, limited by terrain height
3
Water Level Stabilization
Each cell's water level = max(incoming water level, cell height)
4
Calculate Trapped Water
Trapped water = water level - terrain height
Key Takeaway
๐ฏ Key Insight: Use priority queue to process cells in order of water level - this guarantees each cell gets its optimal water level when first processed!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code