407. Trapping Rain Water II
https://leetcode.com/problems/trapping-rain-water-ii/
/*
* @lc app=leetcode id=407 lang=cpp
*
* [407] Trapping Rain Water II
*/
// @lc code=start
class Solution {
public:
int trapRainWater(vector<vector<int>>& heightMap) {
if (heightMap.empty()) return 0;
const int M = heightMap.size(), N = heightMap[0].size();
// min heap
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
vector<vector<bool>> visited(M, vector<bool>(N, false));
vector<vector<int>> dirs{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (i == 0 || i == M - 1 || j == 0 || j == N - 1) {
q.push({heightMap[i][j], i * N + j});
visited[i][j] = true;
}
}
}
int mx = 0, res = 0;
while (!q.empty()) {
const auto t = q.top(); q.pop();
const auto h = t.first, i = t.second / N, j = t.second % N;
mx = max(mx, h);
for (const auto &d : dirs) {
const int x = i + d[0], y = j + d[1];
if (x >= 0 && x < M && y >= 0 && y < N && !visited[x][y]) {
visited[x][y] = true;
if (heightMap[x][y] < mx) res += mx - heightMap[x][y];
q.push({heightMap[x][y], x * N + y});
}
}
}
return res;
}
};
// @lc code=end
Last updated