- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 55 lines of C++ from the credited upstream file 407.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct T {2 int i;3 int j;4 int h; 5};6 7class Solution {8 public:9 int trapRainWater(vector<vector<int>>& heightMap) {10 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};11 const int m = heightMap.size();12 const int n = heightMap[0].size();13 int ans = 0;14 auto compare = [](const T& a, const T& b) { return a.h > b.h; };15 priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);16 vector<vector<bool>> seen(m, vector<bool>(n));17 18 for (int i = 0; i < m; ++i) {19 minHeap.emplace(i, 0, heightMap[i][0]);20 minHeap.emplace(i, n - 1, heightMap[i][n - 1]);21 seen[i][0] = true;22 seen[i][n - 1] = true;23 }24 25 for (int j = 1; j < n - 1; ++j) {26 minHeap.emplace(0, j, heightMap[0][j]);27 minHeap.emplace(m - 1, j, heightMap[m - 1][j]);28 seen[0][j] = true;29 seen[m - 1][j] = true;30 }31 32 while (!minHeap.empty()) {33 const auto [i, j, h] = minHeap.top();34 minHeap.pop();35 for (const auto& [dx, dy] : kDirs) {36 const int x = i + dx;37 const int y = j + dy;38 if (x < 0 || x == m || y < 0 || y == n)39 continue;40 if (seen[x][y])41 continue;42 if (heightMap[x][y] < h) {43 ans += h - heightMap[x][y];44 minHeap.emplace(x, y, h); 45 } else {46 minHeap.emplace(x, y, heightMap[x][y]);47 }48 seen[x][y] = true;49 }50 }51 52 return ans;53 }54};55