407. Trapping Rain Water II
来源:互联网 发布:pr防抖插件 mac 编辑:程序博客网 时间:2024/06/05 02:53
Given an m x n
matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.
Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.
Example:
Given the following 3x6 height map:[ [1,4,3,1,3,2], [3,2,1,3,2,4], [2,3,3,2,3,1]]Return 4.
The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
before the rain.
After the rain, water are trapped between the blocks. The total volume of water trapped is 4.
public class Solution { class Cell { int height, x, y; public Cell(int _height, int _x, int _y) { height = _height; x = _x; y = _y; } } public int trapRainWater(int[][] heightMap) { if (heightMap == null || heightMap.length == 0) { return 0; } int m = heightMap.length; int n = heightMap[0].length; boolean[][] visited = new boolean[m][n]; PriorityQueue<Cell> queue = new PriorityQueue<Cell>(m * n, new Comparator<Cell>() { public int compare(Cell c1, Cell c2) { return c1.height - c2.height; } }); for (int i = 0; i < m; i++) { queue.offer(new Cell(heightMap[i][0], i, 0)); visited[i][0] = true; queue.offer(new Cell(heightMap[i][n - 1], i, n - 1)); visited[i][n - 1] = true; } for (int j = 1; j < n - 1; j++) { queue.offer(new Cell(heightMap[0][j], 0, j)); visited[0][j] = true; queue.offer(new Cell(heightMap[m - 1][j], m - 1, j)); visited[m - 1][j] = true; } int res = 0; int[][] dirs = new int[][]{{0,1}, {0,-1}, {1,0}, {-1,0}}; while (!queue.isEmpty()) { Cell cell = queue.poll(); for (int[] dir: dirs) { int x = cell.x + dir[0], y = cell.y + dir[1]; if (x >= 0 && x < m && y >= 0 && y < n && visited[x][y] == false) { visited[x][y] = true; if (heightMap[x][y] < cell.height) { res += (cell.height - heightMap[x][y]); queue.offer(new Cell(cell.height, x, y)); } else { queue.offer(new Cell(heightMap[x][y], x, y)); } } } } return res; }}
阅读全文
0 0
- 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
- 407. Trapping Rain Water II
- Trapping Rain Water II
- Trapping Rain Water II
- Trapping Rain Water II
- 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
- leetcode 407. Trapping Rain Water II
- leetcode 407. Trapping Rain Water II
- Leetcode 407. Trapping Rain Water II
- Java篇--Java语言的基本语法2
- unity自动化测试框架
- 一个简单的Springmvc Spring Hibernate 整合的案例
- ACboy needs your help
- maven记录
- 407. Trapping Rain Water II
- 车牌号
- 树莓派入门
- 基于物品的协同过滤推荐算法——读“Item-Based Collaborative Filtering Recommendation Algorithms”
- python中若干注意点
- IDUtils
- GFM操作 & 遇到的问题及解决方案
- [第六章]实作嵌入式系统平台 part1
- spring-mvc拦截器和<mvc:annotation-driven />的详解