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; } }
复制代码

 

posted @   blcblc  阅读(319)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示