Trapping Rain Water II
来源:互联网 发布:罗斯福连任 知乎 编辑:程序博客网 时间:2024/06/06 15:53
用优先队列,把边沿的墙全加进去,然后从最低的开始,看四周要不要补水。其他的和第一题很像
public class Solution { class cell implements Comparable{ int x; int y; int height; public cell(int x, int y, int height) { this.x = x; this.y = y; this.height = height; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } @Override public int compareTo( Object o) { cell oo = (cell) o; return height-((cell) o).getHeight(); } } public int trapRainWater(int[][] heightMap) { int width = heightMap.length; if(width<=0)return 0; int length = heightMap[0].length; boolean [][]visted = new boolean[width][length]; PriorityQueue<cell> priorityQueue = new PriorityQueue<>(); if (width == 0 || length == 0)return 0; for (int i=0;i<width;i++){ visted[i][length-1] = true; visted[i][0] = true; priorityQueue.add(new cell(length-1,i,heightMap[i][length-1])); priorityQueue.add(new cell(0,i,heightMap[i][0])); } for (int i=0;i<length;i++){ visted[width-1][i] = true; visted[0][i] =true; priorityQueue.add(new cell(i,width-1,heightMap[width-1][i])); priorityQueue.add(new cell(i,0,heightMap[0][i])); } int res = 0; int[][] fangxiang = {{0,1},{0,-1},{-1,0},{1,0}}; while (!priorityQueue.isEmpty()){ cell ce = priorityQueue.poll(); //System.out.println("height:"+ce.getHeight()); for (int i=0;i<fangxiang.length;i++){ int dx = ce.getX()+fangxiang[i][0]; int dy = ce.getY()+fangxiang[i][1]; if (dx>=0&&dx<length&&dy>=0&&dy<width) { if(!visted[dy][dx]){ cell newCell = new cell(dx, dy, heightMap[dy][dx]); visted[dy][dx] = true; if (ce.compareTo(newCell)>0){ res+=ce.compareTo(newCell); // System.out.println("res:"+res); newCell.setHeight(ce.getHeight()); priorityQueue.add(newCell); continue; }else { priorityQueue.add(newCell); } } } } } return res; }}
0 0
- Trapping Rain Water II
- Trapping Rain Water II
- Trapping Rain Water II
- Trapping Rain Water II
- 407. Trapping Rain Water II
- 407. Trapping Rain Water II
- 407. Trapping Rain Water II
- 407. Trapping Rain Water II
- 407. Trapping Rain Water II
- Leetcode407. Trapping Rain Water II
- 407. Trapping Rain Water II
- N-Queens I,II, Trapping Rain Water
- LintCode 364 Trapping Rain Water II
- Leetcode 407. Trapping Rain Water II
- LeetCode 407. Trapping Rain Water II
- [LeetCode]407. Trapping Rain Water II
- Leetcode 407. Trapping Rain Water II
- Leetcode 407 Trapping Rain Water II
- Excel解决格式与文件扩展名不一致的两种方法
- Oozie 安装部署
- 【并查集】并查集详解(转)
- 从零开始搭建maven+springmvc+mybatis web项目(1)---maven项目目录创建
- VC模拟鼠标的两种方式(SendMessage、mouse_event)
- Trapping Rain Water II
- 解决80端口被占用
- 在Windows下使用Curl工具完美操作ElasticSearch
- AndroidStudio项目提交(更新)到github最详细步骤
- 【Maven】mybatis-generator-maven-plugin 使用
- 校门外的树木
- Qt实现窗体在显示屏旁边自动隐藏(类似QQ)
- 在阿里云盘扩容过程中遇到的坑
- Socket Java设置超时时间