forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path407_trapRainWater.java
56 lines (52 loc) · 1.81 KB
/
407_trapRainWater.java
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
public class Solution {
int[] dx = new int[]{0,1,0,-1};
int[] dy = new int[]{1,0,-1,0};
public int trapRainWater(int[][] heightMap) {
if(heightMap == null || heightMap.length <= 2 || heightMap[0].length <= 2) return 0;
int m = heightMap.length;
int n = heightMap[0].length;
boolean[][] visited = new boolean[m][n];
Comparator<Node> comparator = new Comparator<Node>(){
public int compare(Node a, Node b){
return a.h - b.h;
}
};
Queue<Node> queue = new PriorityQueue<Node>(comparator);
for(int i = 0; i < m; i++){
queue.offer(new Node(i, 0, heightMap[i][0]));
visited[i][0] = true;
queue.offer(new Node(i, n-1, heightMap[i][n-1]));
visited[i][n-1] = true;
}
for(int j = 1; j < n-1; j++){
queue.offer(new Node(0, j, heightMap[0][j]));
visited[0][j] = true;
queue.offer(new Node(m-1, j, heightMap[m-1][j]));
visited[m-1][j] = true;
}
int res = 0;
while(!queue.isEmpty()){
Node node = queue.poll();
for(int dir = 0; dir < 4; dir++){
int x = node.i+dx[dir];
int y = node.j+dy[dir];
if(x >= 0 && y >= 0 && x < m && y <n && !visited[x][y]){
queue.offer(new Node(x, y, Math.max(heightMap[x][y], node.h))); //here is Math.max!!
visited[x][y] = true;
res+= Math.max(0, node.h-heightMap[x][y]);
}
}
}
return res;
}
public class Node{
int i;
int j;
int h;
public Node(int i, int j, int h){
this.i = i;
this.j = j;
this.h = h;
}
}
}