-
Notifications
You must be signed in to change notification settings - Fork 73
/
main2.cpp
84 lines (74 loc) · 2.13 KB
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <cstdlib>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
public:
int trapRainWater(vector<vector<int>>& heightMap) {
int n = heightMap.size();
int m = heightMap[0].size();
int maxHeight = 1000000;
int dirs[] = {-1, 0, 1, 0, -1};
vector<vector<int>> water(n, vector<int>(m, maxHeight));
queue<pair<int,int>> updates;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {
if (water[i][j] > heightMap[i][j]) {
water[i][j] = heightMap[i][j];
updates.push(make_pair(i, j));
}
}
}
}
while (!updates.empty()) {
int x = updates.front().first, y = updates.front().second;
updates.pop();
for (int i = 0; i < 4; ++i) {
int nx = x + dirs[i], ny = y + dirs[i + 1];
if (nx < 0 || nx >= n || ny < 0 || ny >= m) {
continue;
}
if (water[x][y] < water[nx][ny] && water[nx][ny] > heightMap[nx][ny]) {
water[nx][ny] = max(water[x][y], heightMap[nx][ny]);
updates.push(make_pair(nx, ny));
}
}
}
int res = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
res += water[i][j] - heightMap[i][j];
}
}
return res;
}
};
int main(int argc, const char * argv[]) {
Solution sol;
vector<vector<int>> heightMap;
heightMap = {{3,3,3},{3,1,3},{3,3,3}};
cout << sol.trapRainWater(heightMap) << endl;
heightMap = {{3,3,3,3,3},
{3,2,2,2,3},
{3,2,1,2,3},
{3,2,2,2,3},
{3,3,3,3,3}};
cout << sol.trapRainWater(heightMap) << endl;
heightMap = {{1,4,3,1,3,2},{3,2,1,3,2,4},{2,3,3,2,3,1}};
cout << sol.trapRainWater(heightMap) << endl;
heightMap = {{12,13,1,12},
{13,4,13,12},
{13,8,10,12},
{12,13,12,12},
{13,13,13,13}};
cout << sol.trapRainWater(heightMap) << endl;
return 0;
}