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.

解决注水的问题,要从外围入手,一维的问题从两边开始,二维的问题从最外面一圈开始。对于这道题,初始化一个Priorityqueue保存外围的边,和一个visited数组保存是否被访问过。如果Priorityqueue不为空,取出最短的边,遍历四个方向,更新visited,如果比它们高,说明可以注水,更新res,并把这个点存入queue,注意这里的高度是刚才取出的高度,因为刚才的高度才是边;如果比它们矮,不更新res,存入这个更高的高度当边即可。代码如下:

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;    }}

原创粉丝点击