407.trapping-rain-water-ii.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import java.util.PriorityQueue;
  2. class Solution {
  3. class Grid implements Comparable<Grid> {
  4. int val;
  5. int y;
  6. int x;
  7. Grid(int val, int y, int x) {
  8. this.val = val;
  9. this.y = y;
  10. this.x = x;
  11. }
  12. @Override
  13. public int compareTo(Grid that) {
  14. return this.val - that.val; // Don't forget the "public"
  15. }
  16. }
  17. int[] dy = new int[]{0, 1, 0, -1};
  18. int[] dx = new int[]{1, 0, -1, 0};
  19. public int trapRainWater(int[][] heightMap) {
  20. int m, n;
  21. if ((m = heightMap.length) == 0) return 0;
  22. if ((n = heightMap[0].length) == 0) return 0;
  23. PriorityQueue<Grid> pq = new PriorityQueue<>();
  24. boolean[][] used = new boolean[m][n];
  25. for (int i = 0; i < m; i++) {
  26. pq.offer(new Grid(heightMap[i][0], i, 0));
  27. pq.offer(new Grid(heightMap[i][n - 1], i, n - 1));
  28. used[i][0] = true;
  29. used[i][n - 1] = true;
  30. }
  31. for (int j = 1; j < n - 1; j++) {
  32. pq.offer(new Grid(heightMap[0][j], 0, j));
  33. pq.offer(new Grid(heightMap[m - 1][j], m - 1, j));
  34. used[0][j] = true;
  35. used[m - 1][j] = true;
  36. }
  37. int water = 0, height = 0;
  38. while (!pq.isEmpty()) {
  39. Grid curr = pq.poll();
  40. if (height < curr.val) height = curr.val;
  41. else water += height - curr.val;
  42. for (int i = 0; i < 4; i++) {
  43. int ny = curr.y + dy[i], nx = curr.x + dx[i];
  44. if (ny < 0 || m <= ny || nx < 0 || n <= nx || used[ny][nx]) continue;
  45. pq.offer(new Grid(heightMap[ny][nx], ny, nx));
  46. used[ny][nx] = true;
  47. }
  48. }
  49. return water;
  50. }
  51. }