Trapping Rain Water II
Real-world version: Water Held by a Moulded TrayThe statement here is our own: the same inputs, outputs and technique.
A tray is moulded from square cells whose wall heights are given as heightMap. Water is poured over the whole tray until it settles.
Water spreads between cells that share a side, and any water reaching the outside edge of the tray runs off. A cell holds water up to the level the surrounding walls can keep in, and never below its own height.
Return the total volume of water the tray holds once everything has settled.
Examples
Example 1
- Input
- heightMap = [[9, 9, 9, 9, 9], [9, 2, 5, 1, 9], [9, 4, 0, 3, 9], [9, 9, 9, 9, 9]]
- Output
- 39
Walls of 9 surround the tray, so the six inner cells fill to level 9, and the volume is what is left above each of their own heights.
Example 2
- Input
- heightMap = [[3, 3, 3], [3, 4, 3], [3, 3, 3]]
- Output
- 0
The single inner cell stands taller than the wall around it, so nothing collects.
Example 3
- Input
- heightMap = [[5]]
- Output
- 0
A tray one cell across has no inside at all, so nothing can be held.
Constraints
- 1 <= heightMap.length <= 200
- 1 <= heightMap[i].length <= 200
- Every row of heightMap has the same length
- 0 <= heightMap[i][j] <= 2 * 10^4
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def trap_rain_water(heightMap: list[list[int]]) -> int:public int trapRainWater(int[][] heightMap)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Path With Minimum EffortReal-world version: Route With the Gentlest ClimbMedium
- Find the Safest Path in a GridReal-world version: Widest Margin Across the BlockMedium
- Find a Safe Walk Through a GridReal-world version: Shielded Crossing of a Scorched Bay FloorMedium
- Swim in Rising WaterReal-world version: Cutter Power SettingHard