package leetcode;
import java.util.*;
public class Solution{
class Cell{
int col;
int row;
int height;
public Cell(int col,int row,int height){
this.col=col;
this.row=row;
this.height=height;
}
}
public int trapRainWater(int[][] heightMap) {
if(heightMap==null||heightMap.length==0||heightMap[0].length==0)
return 0;
int m=heightMap.length;
int n=heightMap[0].length;
boolean[][] visited=new boolean[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
visited[i][j]=false;
}
PriorityQueue<Cell> queue=new PriorityQueue<>(1,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(i,0,heightMap[i][0]));
queue.offer(new Cell(i,n-1,heightMap[i][n-1]));
visited[i][0]=true;
visited[i][n-1]=true;
}
for(int i=1;i<n-1;i++)//压入 第一行和最后一行
{
queue.offer(new Cell(0,i,heightMap[0][i]));
queue.offer(new Cell(m-1,i,heightMap[m-1][i]));
visited[0][i]=true;
visited[m-1][i]=true;
}
int res=0;
int[][] dirs=new int[][]{{-1,0},{1,0},{0,1},{0,-1}};
while(!queue.isEmpty()){
Cell c=queue.poll ();//从队列中抽取出高度最小的单元
for(int[] dir:dirs){//遍历所有方向
int row=c.row+dir[0];
int col=c.col+dir[1];
if(row>=0&&row<m&&col>=0&&col<n&&!visited[row][col]){
visited[row][col]=true;
res+=Math.max(0, c.height-heightMap[row][col]);
queue.offer(new Cell(row,col,Math.max(c.height, heightMap[row][col])));
}
}
}
return res;
}
public static void main(String[] args){
int[][] a=new int[][]{{1,4,3,1,3,2},{3,2,1,3,2,4},{2,3,3,2,3,1}};
Solution s=new Solution();
System.out.println(s.trapRainWater(a));
}
}
407. Trapping Rain Water II
最新推荐文章于 2021-11-04 09:56:06 发布