Given anm x nmatrix 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:
Bothmandnare 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.
2. Implementation
(1) BFS
publicclassSolution {classCellimplementsComparable<Cell>{int row;int col;int height;publicCell(int row,int col,int height) {this.row= row;this.col= col;this.height= height; }publicintcompareTo(Cell that) {returnthis.height-that.height; } }publicinttrapRainWater(int[][] heightMap) {if (heightMap ==null||heightMap.length==0|| heightMap[0].length==0) {return0; }int m =heightMap.length, n = heightMap[0].length;boolean[][] visited =newboolean[m][n];PriorityQueue<Cell> queue =newPriorityQueue<>();for (int i =0; i < m; i++) {for (int j =0; j < n; j++) {if (i ==0|| i == m -1|| j ==0|| j == n -1) {queue.add(newCell(i, j, heightMap[i][j])); visited[i][j] =true; } } }int[][] directions = {{-1,0}, {1,0}, {0,-1}, {0,1}};int curMaxHeight =0;int res =0;while (!queue.isEmpty()) {Cell curCell =queue.remove(); curMaxHeight =Math.max(curMaxHeight,curCell.height);for (int[] direction : directions) {int nextRow =curCell.row+ direction[0];int nextCol =curCell.col+ direction[1];if (isValid(heightMap, nextRow, nextCol, visited)) { visited[nextRow][nextCol] =true;queue.add(newCell(nextRow, nextCol, heightMap[nextRow][nextCol]));if (heightMap[nextRow][nextCol] < curMaxHeight) { res += curMaxHeight - heightMap[nextRow][nextCol]; } } } }return res; }publicbooleanisValid(int[][] heightMap,int row,int col,boolean[][] visited) {return row >=0&& row <heightMap.length&& col >=0&& col < heightMap[0].length&&!visited[row][col]; }}
3. Time & Space Complexity
BFS: 时间复杂度O(mn), 空间复杂度O(mn)
After the rain, water are trapped between the blocks. The total volume of water trapped is 4.