Practice › Heap & Priority Queue
Trapping Rain Water II
Hard · Heap & Priority Queue · Asked at Google, Amazon, Microsoft, Twitter
An R × C grid gives the height of each unit cell of an elevation map. After it rains, water stays in cells surrounded by higher walls (it can flow up, down, left or right, and anything reaching the border spills off). Print the total volume of water trapped.
Input
First line: R C. Next R lines: C heights.
Output
The trapped volume.
Constraints
- 1 ≤ R, C ≤ 200
- 0 ≤ height ≤ 2 × 10^4
The water level of a cell is decided by the lowest point of the wall around it. Start with all border cells in a min-heap. Repeatedly pop the lowest cell and visit its unvisited neighbours: a lower neighbour holds (current level − its height) water, and is pushed with level max(current level, its height).
Example 1
Input
3 6 1 4 3 1 3 2 3 2 1 3 2 4 2 3 3 2 3 1
Output
4
Example 2
Input
5 5 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
Hints
- Water over a cell is limited by the lowest point of the "wall" around it, all the way to the border.
- Start from the border (it holds no water) and move inward from the lowest wall first.
- A min-heap always tells you the lowest point of the current boundary.
Approach
Push every border cell into a min-heap keyed by height and mark it visited. Pop the lowest cell (level = its key) and look at its unvisited neighbours: a neighbour lower than level traps level − height units; push it with key max(level, height), because water fills it up to level. Since we always expand from the lowest boundary point, each cell's water level is decided correctly the first time it is reached.
Complexity: O(R · C · log(R · C)) time · O(R · C) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int R, C;
cin >> R >> C;
vector<vector<int>> g(R, vector<int>(C));
for (auto &row : g)
for (auto &x : row) cin >> x;
vector<vector<bool>> seen(R, vector<bool>(C, false));
priority_queue<array<int, 3>, vector<array<int, 3>>, greater<array<int, 3>>> pq;
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (i == 0 || j == 0 || i == R - 1 || j == C - 1) {
seen[i][j] = true;
pq.push({g[i][j], i, j});
}
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
long long water = 0;
while (!pq.empty()) {
array<int, 3> t = pq.top();
pq.pop();
for (int d = 0; d < 4; d++) {
int a = t[1] + dx[d], b = t[2] + dy[d];
if (a < 0 || b < 0 || a >= R || b >= C || seen[a][b]) continue;
seen[a][b] = true;
water += max(0, t[0] - g[a][b]);
pq.push({max(t[0], g[a][b]), a, b});
}
}
cout << water << "\n";
return 0;
}Python solution
import heapq
import sys
data = list(map(int, sys.stdin.read().split()))
R, C = data[0], data[1]
g = [data[2 + i * C : 2 + (i + 1) * C] for i in range(R)]
seen = [[False] * C for _ in range(R)]
pq = []
for i in range(R):
for j in range(C):
if i == 0 or j == 0 or i == R - 1 or j == C - 1:
seen[i][j] = True
pq.append((g[i][j], i, j))
heapq.heapify(pq)
water = 0
while pq:
level, x, y = heapq.heappop(pq)
for a, b in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
if 0 <= a < R and 0 <= b < C and not seen[a][b]:
seen[a][b] = True
h = g[a][b]
if h < level:
water += level - h
heapq.heappush(pq, (max(level, h), a, b))
print(water)Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int R = (int) in.nval;
in.nextToken();
int C = (int) in.nval;
int[][] g = new int[R][C];
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++) {
in.nextToken();
g[i][j] = (int) in.nval;
}
boolean[][] seen = new boolean[R][C];
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (i == 0 || j == 0 || i == R - 1 || j == C - 1) {
seen[i][j] = true;
pq.add(new int[] {g[i][j], i, j});
}
int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};
long water = 0;
while (!pq.isEmpty()) {
int[] t = pq.poll();
for (int d = 0; d < 4; d++) {
int a = t[1] + dx[d], b = t[2] + dy[d];
if (a < 0 || b < 0 || a >= R || b >= C || seen[a][b]) continue;
seen[a][b] = true;
water += Math.max(0, t[0] - g[a][b]);
pq.add(new int[] {Math.max(t[0], g[a][b]), a, b});
}
}
System.out.println(water);
}
}