码迷,mamicode.com
首页 > 移动开发 > 详细

[LeetCode] 407. Trapping Rain Water II

时间:2017-06-11 15:42:13      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:offer   while   queue   ref   rand   empty   app   ++   lan   

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

标签:offer   while   queue   ref   rand   empty   app   ++   lan   

原文地址:http://www.cnblogs.com/chencode/p/trapping-rain-water-ii.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!