-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek8 Leetcode 407. Trapping Rain Water II
More file actions
53 lines (47 loc) · 1.68 KB
/
week8 Leetcode 407. Trapping Rain Water II
File metadata and controls
53 lines (47 loc) · 1.68 KB
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
public class Solution {
public int trapRainWater(int[][] heightMap) {
class Cell{
int x, y,h;
Cell(int x, int y, int height){
this.x = x;
this.y = y;
h = height;
}
}
if (heightMap == null || heightMap.length == 0 || heightMap[0].length == 0) {
return 0;
}
int m = heightMap.length;
int n = heightMap[0].length;
PriorityQueue<Cell> pq = new PriorityQueue<>((v1,v2)->v1.h - v2.h);
boolean[][] visited = new boolean[m][n];
for(int i = 0; i < n; i++){
visited[0][i] = true;
visited[m-1][i] = true;
pq.offer(new Cell(0, i, heightMap[0][i]));
pq.offer(new Cell(m-1, i, heightMap[m-1][i]));
}
for(int i = 1; i < m-1; i++){
visited[i][0] = true;
visited[i][n-1] = true;
pq.offer(new Cell(i, 0, heightMap[i][0]));
pq.offer(new Cell(i, n-1, heightMap[i][n-1]));
}
int[] xs = {0, 0, 1, -1};
int[] ys = {1, -1, 0, 0};
int sum = 0;
while (!pq.isEmpty()) {
Cell cell = pq.poll();
for (int i = 0; i < 4; i++) {
int nx = cell.x + xs[i];
int ny = cell.y + ys[i];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visited[nx][ny]) {
visited[nx][ny] = true;
sum += Math.max(0, cell.h - heightMap[nx][ny]);
pq.offer(new Cell(nx, ny, Math.max(heightMap[nx][ny], cell.h)));
}
}
}
return sum;
}
}