Skip to content

Commit 577f511

Browse files
authored
Create 407. Trapping Rain Water II (#692)
2 parents 74efcdb + bc9f0b1 commit 577f511

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

407. Trapping Rain Water II

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
class Solution {
2+
public:
3+
int trapRainWater(vector<vector<int>>& heightMap) {
4+
if (heightMap.empty() || heightMap[0].empty()) return 0;
5+
6+
int rows = heightMap.size(), cols = heightMap[0].size();
7+
vector<vector<int>> graph(rows * cols + 1);
8+
int virtualStart = rows * cols;
9+
10+
// Direction vectors for moving in 4 directions
11+
vector<int> dx = {0, 0, 1, -1};
12+
vector<int> dy = {1, -1, 0, 0};
13+
14+
// Build the graph
15+
for (int i = 0; i < rows; i++) {
16+
for (int j = 0; j < cols; j++) {
17+
int currentCell = i * cols + j;
18+
19+
// Connect boundary cells to virtual start node
20+
if (i == 0 || i == rows - 1 || j == 0 || j == cols - 1) {
21+
graph[virtualStart].push_back(currentCell);
22+
}
23+
24+
// Connect current cell to its neighbors
25+
for (int k = 0; k < 4; k++) {
26+
int x = i + dx[k], y = j + dy[k];
27+
if (x >= 0 && x < rows && y >= 0 && y < cols) {
28+
graph[currentCell].push_back(x * cols + y);
29+
}
30+
}
31+
}
32+
}
33+
34+
// Dijkstra-like BFS to calculate distances
35+
auto calculateDistances = [&](int start) {
36+
vector<int> dist(graph.size(), INT_MAX / 2);
37+
dist[start] = 0;
38+
39+
// Min-heap to prioritize cells with smaller heights
40+
set<pair<int, int>> pq; // {distance, node}
41+
pq.insert({0, start});
42+
43+
while (!pq.empty()) {
44+
auto [currentDist, currentNode] = *pq.begin();
45+
pq.erase(pq.begin());
46+
47+
for (int neighbor : graph[currentNode]) {
48+
int weight = heightMap[neighbor / cols][neighbor % cols];
49+
if (max(currentDist, weight) < dist[neighbor]) {
50+
pq.erase({dist[neighbor], neighbor});
51+
dist[neighbor] = max(currentDist, weight);
52+
pq.insert({dist[neighbor], neighbor});
53+
}
54+
}
55+
}
56+
57+
return dist;
58+
};
59+
60+
vector<int> dist = calculateDistances(virtualStart);
61+
62+
// Calculate trapped water
63+
int trappedWater = 0;
64+
for (int i = 0; i < rows; i++) {
65+
for (int j = 0; j < cols; j++) {
66+
int cell = i * cols + j;
67+
int boundaryHeight = dist[cell];
68+
if (boundaryHeight > heightMap[i][j]) {
69+
trappedWater += boundaryHeight - heightMap[i][j];
70+
}
71+
}
72+
}
73+
74+
return trappedWater;
75+
}
76+
};

0 commit comments

Comments
 (0)