Advertisement
nikunjsoni

407

May 27th, 2021
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int trapRainWater(vector<vector<int>>& heightMap) {
  4.         int rows = heightMap.size(), cols=heightMap[0].size();
  5.         priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
  6.         vector<bool> vis(rows*cols, false);
  7.        
  8.         for(int i=0; i<cols; i++){
  9.             pq.push({heightMap[0][i], i});
  10.             vis[i] = true;
  11.             if(rows>1){
  12.                 pq.push({heightMap[rows-1][i], cols*(rows-1)+i});
  13.                 vis[cols*(rows-1)+i] = true;
  14.             }
  15.         }
  16.         for(int i=0; i<rows; i++){
  17.             pq.push({heightMap[i][0], cols*i});
  18.             vis[cols*i] = true;
  19.             if(cols>1){
  20.                 pq.push({heightMap[i][cols-1], cols*i+cols-1});
  21.                 vis[cols*i+cols-1] = true;
  22.             }
  23.         }
  24.        
  25.         int ans = 0;
  26.         int curMax = 0;
  27.         int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
  28.         while(!pq.empty()){
  29.             auto p = pq.top(); pq.pop();
  30.             int curX = p.second/cols, curY = p.second%cols;
  31.             curMax = max(curMax, p.first);
  32.             for(int i=0; i<4; i++){
  33.                 int nextX = curX+dir[i][0], nextY = curY+dir[i][1];
  34.                 if(nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols || vis[nextX*cols+nextY]) continue;
  35.                 ans += (heightMap[nextX][nextY] < curMax) ? (curMax-heightMap[nextX][nextY]) : 0;
  36.                 pq.push({heightMap[nextX][nextY], nextX*cols+nextY});
  37.                 vis[nextX*cols+nextY] = true;
  38.             }
  39.         }
  40.         return ans;
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement