Trapping Rain Water II
Hard
Topics
Given an m x n matrix of non-negative integers representing the height of each cell, return the volume of water that can be trapped after raining.
Example 1
height+water. A cell’s water level is set by the lowest ridge it must cross to escape, so the border can never hold water and the interior is solved by growing inward from the lowest wall. Total trapped: 4.Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] Output: 4
Example 2
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
Constraints
- m == heightMap.length
- n == heightMap[i].length
- 1 <= m, n <= 200
- 0 <= heightMap[i][j] <= 2*10^4.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The 1-D version of this problem has a clean answer: water over a bar is min(maxLeft, maxRight) - height, so two prefix scans settle it. The instinct is to carry that over by taking the min of the four directional maxima. It does not work. In two dimensions water does not escape along a row or a column, it escapes along any path to the border, including ones that wind diagonally around obstacles. A cell can be hemmed in along both axes and still drain through a gap that no row-or-column maximum knows about.
So ask the right question. The water level at a cell is decided by the lowest point on the best escape route — of every path from that cell to the border, take the one whose highest obstacle is smallest, and that obstacle's height is the level. That is a bottleneck-shortest-path problem, not a prefix-max problem.
Rather than solve it per cell, flood the whole grid inward from the rim at once. The border is where water spills out, so it holds none. Keep the current rim in a min-heap and always process its lowest cell, because the lowest point on the rim is where the basin spills first and therefore fixes the level for whatever sits behind it.
When the lowest rim cell at level L has an unvisited neighbour of terrain height h:
h < L— the neighbour is a dip behind a wall of heightL, so it fills withL - hwater, and its surface joins the rim at levelL.h >= L— the neighbour is higher than the spill point, so it stays dry and joins the rim at its own heighth.
Both cases push max(L, h), which is why one line covers them. Processing in increasing order of level is what makes a visited cell final: nothing cheaper can arrive later to lower it.
💡 This is Dijkstra with max in place of + — the cost of a path is its highest barrier rather than its total, and the greedy pop is correct for the same reason it is in Dijkstra.
Approach
- If either dimension is under 3 there is no interior cell, so return 0.
- Push every border cell into a min-heap keyed on its own height and mark it visited. These are the initial rim.
- Pop the lowest cell, giving level
L. For each unvisited orthogonal neighbour of heighth: mark it visited, addmax(0, L - h)to the total, and push it at levelmax(L, h). - Stop when the heap drains. Every cell has then been assigned its final level exactly once.
Dry Run
heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]. It is 3x6, so the only interior cells are the four at row 1, columns 1..4, with heights 2, 1, 3, 2. Expected answer 4.
rim starts as all 14 border cells, keyed on their own heights
pop level=1 at (0,3) -> neighbour (1,3) h=3 h >= L, stays dry
water += 0 total 0
pushed at max(1,3) = 3
pop level=3 at (0,2) -> neighbour (1,2) h=1 dip behind a wall of 3
water += 3-1 = 2 total 2
pushed at 3
pop level=3 at (0,4) -> neighbour (1,4) h=2 water += 3-2 = 1 total 3
pushed at 3
pop level=3 at (1,0) -> neighbour (1,1) h=2 water += 3-2 = 1 total 4
pushed at 3
heap drains over the remaining border cells; no unvisited neighbours left
answer 4The instructive pop is the first. Cell (0,3) has height 1 and is the lowest thing on the rim, but its inward neighbour (1,3) stands at 3 — taller than the spill point, so it takes no water and rejoins the rim at its own height. Had we processed a taller rim cell first we would have wrongly flooded it. That ordering is exactly what the heap enforces.
Complexity
- Time — O(m*n log(m*n)): every cell is pushed and popped at most once, and each heap operation is logarithmic in the number of cells held. The border seeding is O(m*n) pushes. With
m, n <= 200that is 40,000 cells and roughly 40,000 * 16 heap steps. - Space — O(m*n): the visited grid, plus a heap that in the worst case holds most of the grid at once. There is no way around the visited grid here — unlike the 1-D problem, which is O(1) with two pointers.
Common Pitfalls
- Porting the 1-D formula and taking
minof the four directional maxima. It overestimates, because water can escape by a winding path those maxima cannot see. This is the mistake the problem is built to catch. - Pushing the neighbour at its own height instead of
max(L, h). A filled dip's surface is atL, and forgetting that lets later cells drain through water that is already standing. - Marking visited at pop time rather than push time. The same cell then enters the heap from several neighbours and its water is counted more than once.
- Keying the heap on terrain height rather than water level. They coincide only on the border; after the first fill the level is what orders correctly.
- Including diagonals as neighbours. Water moves orthogonally between cells here, even though the escape path argument is what motivates the algorithm.
- Skipping the
rows < 3 || cols < 3guard. It is not strictly needed for correctness — with no interior cell nothing is ever filled — but the constraints allow1 x 1, and the early return makes that explicit. - Letting the running total overflow a 32-bit int on a large grid. 200 x 200 cells at up to 2*10^4 each is about 8*10^8, which fits, but it is close enough that accumulating in a 64-bit type is the safer habit.
Full Solution — all languages
import heapq
class Solution:
def trapRainWater(self, heightMap):
if not heightMap or not heightMap[0]:
return 0
rows, cols = len(heightMap), len(heightMap[0])
if rows < 3 or cols < 3:
return 0 # no interior cell, so nothing can be enclosed
visited = [[False] * cols for _ in range(rows)]
wall = [] # min-heap of (water level, row, col)
# The border can never hold water: it is the rim the basin drains over.
for r in range(rows):
for c in range(cols):
if r in (0, rows - 1) or c in (0, cols - 1):
heapq.heappush(wall, (heightMap[r][c], r, c))
visited[r][c] = True
water = 0
while wall:
# The lowest unprocessed wall decides where the basin spills first.
level, r, c = heapq.heappop(wall)
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and not visited[nr][nc]:
visited[nr][nc] = True
# Below the surrounding level, the gap fills; otherwise it is dry
# and becomes part of the rim at its own height.
water += max(0, level - heightMap[nr][nc])
heapq.heappush(wall, (max(level, heightMap[nr][nc]), nr, nc))
return waterimport java.util.*;
class Solution {
public int trapRainWater(int[][] heightMap) {
if (heightMap == null || heightMap.length == 0 || heightMap[0].length == 0) return 0;
int rows = heightMap.length, cols = heightMap[0].length;
if (rows < 3 || cols < 3) return 0; // no interior cell to enclose water
boolean[][] visited = new boolean[rows][cols];
// min-heap of {water level, row, col}
PriorityQueue<int[]> wall = new PriorityQueue<>((x, y) -> Integer.compare(x[0], y[0]));
// The border can never hold water: it is the rim the basin drains over.
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {
wall.add(new int[]{heightMap[r][c], r, c});
visited[r][c] = true;
}
}
}
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int water = 0;
while (!wall.isEmpty()) {
// The lowest unprocessed wall decides where the basin spills first.
int[] cell = wall.poll();
int level = cell[0], r = cell[1], c = cell[2];
for (int[] d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || visited[nr][nc]) continue;
visited[nr][nc] = true;
// Below the surrounding level it fills; otherwise it is dry and joins
// the rim at its own height.
water += Math.max(0, level - heightMap[nr][nc]);
wall.add(new int[]{Math.max(level, heightMap[nr][nc]), nr, nc});
}
}
return water;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int trapRainWater(vector<vector<int>>& heightMap) {
if (heightMap.empty() || heightMap[0].empty()) return 0;
int rows = heightMap.size(), cols = heightMap[0].size();
if (rows < 3 || cols < 3) return 0; // no interior cell to enclose water
vector<vector<char>> visited(rows, vector<char>(cols, 0));
// min-heap of (water level, row, col)
priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>,
greater<tuple<int,int,int>>> wall;
// The border can never hold water: it is the rim the basin drains over.
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {
wall.emplace(heightMap[r][c], r, c);
visited[r][c] = 1;
}
}
}
const int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
long long water = 0;
while (!wall.empty()) {
// The lowest unprocessed wall decides where the basin spills first.
auto [level, r, c] = wall.top();
wall.pop();
for (int k = 0; k < 4; k++) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || visited[nr][nc]) continue;
visited[nr][nc] = 1;
// Below the surrounding level it fills; otherwise it is dry and joins
// the rim at its own height.
water += max(0, level - heightMap[nr][nc]);
wall.emplace(max(level, heightMap[nr][nc]), nr, nc);
}
}
return (int) water;
}
};/**
* @param {number[][]} heightMap
* @return {number}
*/
var trapRainWater = function (heightMap) {
if (!heightMap || !heightMap.length || !heightMap[0].length) return 0;
const rows = heightMap.length, cols = heightMap[0].length;
if (rows < 3 || cols < 3) return 0; // no interior cell to enclose water
// Binary min-heap of [level, row, col]; no built-in priority queue in JS.
const wall = [];
const swap = (i, j) => { const t = wall[i]; wall[i] = wall[j]; wall[j] = t; };
const push = (item) => {
wall.push(item);
let i = wall.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (wall[p][0] <= wall[i][0]) break;
swap(p, i); i = p;
}
};
const pop = () => {
const top = wall[0], last = wall.pop();
if (wall.length) {
wall[0] = last;
let i = 0;
for (;;) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < wall.length && wall[l][0] < wall[m][0]) m = l;
if (r < wall.length && wall[r][0] < wall[m][0]) m = r;
if (m === i) break;
swap(m, i); i = m;
}
}
return top;
};
const visited = Array.from({ length: rows }, () => new Array(cols).fill(false));
// The border can never hold water: it is the rim the basin drains over.
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (r === 0 || r === rows - 1 || c === 0 || c === cols - 1) {
push([heightMap[r][c], r, c]);
visited[r][c] = true;
}
}
}
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
let water = 0;
while (wall.length) {
// The lowest unprocessed wall decides where the basin spills first.
const [level, r, c] = pop();
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || visited[nr][nc]) continue;
visited[nr][nc] = true;
// Below the surrounding level it fills; otherwise it is dry and joins
// the rim at its own height.
water += Math.max(0, level - heightMap[nr][nc]);
push([Math.max(level, heightMap[nr][nc]), nr, nc]);
}
}
return water;
};