LeetCode 778. 水位上升的泳池中游泳
在一个 N x N 的坐标方格 grid 中,每一个方格的值 grid[i][j] 表示在位置 (i,j) 的平台高度。
现在开始下雨了。当时间为 t 时,此时雨水导致水池中任意位置的水位为 t 。你可以从一个平台游向四周相邻的任意一个平台,但是前提是此时水位必须同时淹没这两个平台。假定你可以瞬间移动无限距离,也就是默认在方格内部游动是不耗时的。当然,在你游泳的时候你必须待在坐标方格里面。
你从坐标方格的左上平台 (0,0) 出发。最少耗时多久你才能到达坐标方格的右下平台 (N-1, N-1)?
题解:
分析:如果直接使用广度优先搜索,需要指数级别的时间复杂度,因此,可以采用优先队列+广度优先搜索。如果当前节点的水位大于下一节点,那么最少时间为当前节点,否则就得更新最优值。当第一次遇到终点时,即为最优值。
class Solution {
public int swimInWater(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0)
return 0;
int n = grid.length, m = grid[0].length;
PriorityQueue<Node> queue = new PriorityQueue<Node>(new Comparator<Node>(){
public int compare(Node node1, Node node2){
return node1.val - node2.val;
}
});
boolean[][] vis = new boolean[n][m];
queue.offer(new Node(0,0,grid[0][0]));
int ret = 0;
int[][] dir = {{0,1},{0,-1},{1,0},{-1,0}};
while(!queue.isEmpty()){
Node top = queue.poll();
ret = Math.max(top.val,ret);
if(top.x == n - 1 && top.y == m - 1)
return ret;
if(vis[top.x][top.y])
continue;
vis[top.x][top.y] = true;
for(int i = 0; i < 4; i++){
int nx = top.x + dir[i][0], ny = top.y + dir[i][1];
if(nx >= 0 && nx < n && ny >= 0 && ny < m)
queue.offer(new Node(nx,ny,grid[nx][ny]));
}
}
return 0;
}
}
class Node{
int x;
int y;
int val;
public Node(int x, int y, int val){
this.x = x;
this.y = y;
this.val = val;
}
}
题目链接:
https://leetcode-cn.com/problems/swim-in-rising-water/
题解参考:
https://leetcode-cn.com/problems/swim-in-rising-water/solution/shui-wei-shang-sheng-de-yong-chi-zhong-y-xm9i/