Trapping Rain Water II - Problem
Imagine a 2D landscape after heavy rainfall! ๐ŸŒง๏ธ

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
Water Trapping VisualizationH:3H:5H:2H:4H:1H:6WaterProcessing Order:1Process boundaries first2Expand to neighbors3Calculate water levels๐ŸŒŠ Water flows from boundaries inward, creating optimal water levels
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!
Asked in
Google 45 Amazon 38 Meta 28 Microsoft 22 Apple 15
68.2K Views
Medium-High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen