LeetCode 778. 水位上升的泳池中游泳

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值