leetcode 407 收集雨水(java 搜索)

 

 二維數組存儲的是每個單元的高度,求最多接多少體積的雨水

首先想到的就是找到最低點

 

 

  

  注意看後兩個圖,當水超過3的時候,可以從綠的的點流進內部

所以可以想象內部現在的水的高度可以達到3,減去原來的體積,就是水的體積

 

 太機智了吧

這個就是想象,想象水流進來的感覺,從內部往外面擴展,找不到什麼規律

 

 要注意的一點就是,四周的點是沒什麼用的,因爲首先積水肯定不會在四周

然後內部有積水後,將數組中的高度重新賦值爲當前積水高度

public class Solution {

    public class Cell {
        int row;
        int col;
        int height;
        public Cell(int row, int col, int height) {
            this.row = row;
            this.col = col;
            this.height = height;
        }
    }

    public int trapRainWater(int[][] heights) {
        if (heights == null || heights.length == 0 || heights[0].length == 0)
            return 0;

        PriorityQueue<Cell> queue = new PriorityQueue<>(1, new Comparator<Cell>(){
            public int compare(Cell a, Cell b) {
                return a.height - b.height;
            }
        });
        
        int m = heights.length;
        int n = heights[0].length;
        boolean[][] visited = new boolean[m][n];

        // Initially, add all the Cells which are on borders to the queue.
        for (int i = 0; i < m; i++) {
            visited[i][0] = true;
            visited[i][n - 1] = true;
            queue.offer(new Cell(i, 0, heights[i][0]));
            queue.offer(new Cell(i, n - 1, heights[i][n - 1]));
        }

        for (int i = 0; i < n; i++) {
            visited[0][i] = true;
            visited[m - 1][i] = true;
            queue.offer(new Cell(0, i, heights[0][i]));
            queue.offer(new Cell(m - 1, i, heights[m - 1][i]));
        }

        // from the borders, pick the shortest cell visited and check its neighbors:
        // if the neighbor is shorter, collect the water it can trap and update its height as its height plus the water trapped
       // add all its neighbors to the queue.
        int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int res = 0;
        while (!queue.isEmpty()) {
            Cell cell = queue.poll();
            for (int[] dir : dirs) {
                int row = cell.row + dir[0];
                int col = cell.col + dir[1];
                if (row >= 0 && row < m && col >= 0 && col < n && !visited[row][col]) {
                    visited[row][col] = true;
                    res += Math.max(0, cell.height - heights[row][col]);
                    queue.offer(new Cell(row, col, Math.max(heights[row][col], cell.height)));
                }
            }
        }
        
        return res;
    }
}

 太難了,所以看得網上大神做的複製過來

大神厲害,自定義一個cell結構

創建具有 PriorityQueue初始容量的PriorityQueue,根據指定的比較器對其元素進行排序。

值得注意的是,優先級隊列的默認排序是數值大的優先級高,排在前面,所以我們需要重寫排序函數

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章