[LeetCode] 407. Trapping Rain Water II
Posted 努橙刷题编
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 407. Trapping Rain Water II相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/trapping-rain-water-ii/
public class Solution { class Cell { public int x; public int y; public int value; public Cell(int x, int y, int value) { this.x = x; this.y = y; this.value = value; } } public int trapRainWater(int[][] heightMap) { int level = 0; int result = 0; if (heightMap == null || heightMap.length == 0 || heightMap[0].length == 0) { return result; } boolean[][] visited = new boolean[heightMap.length][heightMap[0].length]; int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; PriorityQueue<Cell> queue = new PriorityQueue<Cell>(new Comparator<Cell>() { public int compare(Cell c1, Cell c2) { return c1.value - c2.value; } }); for (int i = 0; i < heightMap.length; i++) { for (int j = 0; j < heightMap[0].length; j++) { if (i == 0 || j == 0 || i == heightMap.length - 1 || j == heightMap[0].length - 1) { queue.offer(new Cell(i, j, heightMap[i][j])); visited[i][j] = true; } else { visited[i][j] = false; } } } while (!queue.isEmpty()) { Cell current = queue.poll(); int height = current.value; level = Math.max(height, level); for (int[] move : dir) { int x = current.x + move[0]; int y = current.y + move[1]; if (x >= 0 && x < heightMap.length && y >= 0 && y < heightMap[0].length && visited[x][y] == false) { result += heightMap[x][y] < level ? level - heightMap[x][y] : 0; visited[x][y] = true; queue.offer(new Cell(x, y, heightMap[x][y])); } } } return result; } }
参考:http://www.cnblogs.com/grandyang/p/5928987.html
以上是关于[LeetCode] 407. Trapping Rain Water II的主要内容,如果未能解决你的问题,请参考以下文章
leetcode407 Trapping rain water II
[leetcode] 407. Trapping Rain Water II