C++ | Leetcode C++题解之第407题接雨水II

打印 上一主题 下一主题

主题 1056|帖子 1056|积分 3168

题目:

题解:
  1. class Solution {
  2. public:
  3.     int trapRainWater(vector<vector<int>>& heightMap) {
  4.         int m = heightMap.size(), n = heightMap[0].size();
  5.         int maxHeight = 0;
  6.         int dirs[] = {-1, 0, 1, 0, -1};
  7.         for (int i = 0; i < m; ++i) {
  8.             maxHeight = max(maxHeight, *max_element(heightMap[i].begin(), heightMap[i].end()));
  9.         }
  10.         vector<vector<int>> water(m, vector<int>(n, maxHeight));
  11.         queue<pair<int,int>> qu;
  12.         for (int i = 0; i < m; ++i) {
  13.             for (int j = 0; j < n; ++j) {
  14.                 if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
  15.                     if (water[i][j] > heightMap[i][j]) {
  16.                         water[i][j] = heightMap[i][j];
  17.                         qu.push(make_pair(i, j));
  18.                     }
  19.                 }
  20.             }
  21.         }        
  22.         while (!qu.empty()) {
  23.             int x = qu.front().first, y = qu.front().second;
  24.             qu.pop();
  25.             for (int i = 0; i < 4; ++i) {
  26.                 int nx = x + dirs[i], ny = y + dirs[i + 1];
  27.                 if (nx < 0 || nx >= m || ny < 0 || ny >= n) {
  28.                     continue;
  29.                 }
  30.                 if (water[x][y] < water[nx][ny] && water[nx][ny] > heightMap[nx][ny]) {
  31.                     water[nx][ny] = max(water[x][y], heightMap[nx][ny]);
  32.                     qu.push(make_pair(nx, ny));
  33.                 }
  34.             }
  35.         }
  36.         int res = 0;
  37.         for (int i = 0; i < m; ++i) {
  38.             for (int j = 0; j < n; ++j) {
  39.                 res += water[i][j] - heightMap[i][j];
  40.             }
  41.         }
  42.         return res;
  43.     }
  44. };
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

郭卫东

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表