trapping-rain-water-ii

https://leetcode.com/problems/trapping-rain-water-ii/

// https://discuss.leetcode.com/topic/60418/java-solution-using-priorityqueue/2
// 这个解法真的好棒,真的太棒了
// 一维的也能搞定

// 利用一个PriorityQueue,从小往大排的 import java.util.Comparator; import java.util.PriorityQueue; public class Solution { public class Cell { int row; int col; int height; public Cell(int r, int c, int h) { row = r; col = c; height = h; } } public int trapRainWater(int[][] heightMap) { if (heightMap == null || heightMap.length == 0 || heightMap[0].length == 0) { return 0; } int rows = heightMap.length; int cols = heightMap[0].length; boolean [][]visited = new boolean[rows][cols];
     // 注意,是从小往大排 PriorityQueue
<Cell> pq = new PriorityQueue<Cell>(1, new Comparator<Cell>(){ public int compare(Cell a, Cell b) { return a.height - b.height; } }); for (int i=0; i<rows; i++) { visited[i][0] = true; visited[i][cols-1] = true; pq.offer(new Cell(i, 0, heightMap[i][0])); pq.offer(new Cell(i, cols-1, heightMap[i][cols-1])); } for (int i=0; i<cols; i++) { visited[0][i] = true; visited[rows-1][i] = true; pq.offer(new Cell(0, i, heightMap[0][i])); pq.offer(new Cell(rows-1, i, heightMap[rows-1][i])); } int result = 0; int [][]dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; while (!pq.isEmpty()) { Cell cl = pq.poll(); for (int i=0; i<4; i++) { int r = cl.row + dirs[i][0]; int c = cl.col + dirs[i][1]; if (r < 0 || r >= rows || c < 0 || c >= cols || visited[r][c]) { continue; } int newHt = heightMap[r][c]; if (heightMap[r][c] < cl.height) { result += cl.height - heightMap[r][c]; newHt = cl.height; } pq.offer(new Cell(r, c, newHt)); visited[r][c] = true; } } return result; } }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值