Leetcode 778. 水位上升的泳池中游泳 C++

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

题目

在一个 N x N 的坐标方格 grid 中,每一个方格的值 grid[i][j] 表示在位置 (i,j) 的平台高度。

现在开始下雨了。当时间为 t 时,此时雨水导致水池中任意位置的水位为 t 。你可以从一个平台游向四周相邻的任意一个平台,但是前提是此时水位必须同时淹没这两个平台。假定你可以瞬间移动无限距离,也就是默认在方格内部游动是不耗时的。当然,在你游泳的时候你必须待在坐标方格里面。

你从坐标方格的左上平台 (0,0) 出发。最少耗时多久你才能到达坐标方格的右下平台 (N-1, N-1)?

测试样例

示例 1:

输入: [[0,2],[1,3]]
输出: 3
解释:
时间为0时,你位于坐标方格的位置为 (0, 0)。
此时你不能游向任意方向,因为四个相邻方向平台的高度都大于当前时间为 0 时的水位。

等时间到达 3 时,你才可以游向平台 (1, 1). 因为此时的水位是 3,坐标方格中的平台没有比水位 3 更高的,所以你可以游向坐标方格中的任意位置

示例2:

输入: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
输出: 16
解释:
 0  1  2  3  4
24 23 22 21  5
12 13 14 15 16
11 17 18 19 20
10  9  8  7  6

最终的路线用加粗进行了标记。
我们必须等到时间为 16,此时才能保证平台 (0, 0) 和 (4, 4) 是连通的

提示:

  1. 2 <= N <= 50.
  2. grid[i][j] 位于区间 [0, …, N*N - 1] 内。

题解

优先队列
我们建立一个类,表示达到该地方时的时间。我们利用优先队列进行遍历,显然,当出队列时,便是到达这个地方的最短时间,我们进行标记,以防再次到这个地方。详细过程见代码

代码

class Place{
public:
    int x;
    int y;
    int time;
    Place(int x,int y,int time){
        this->x = x;
        this->y = y;
        this->time = time;
    }
    bool operator < (const Place p) const{
        return this->time > p.time;
    }
};
class Solution {
public:
    int swimInWater(vector<vector<int>>& grid) {
        priority_queue<Place> pq;
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> visit(m,vector<int>(n,0));
        int dir[4][2] = {
            {-1,0},{0,1},{1,0},{0,-1}
        };
        pq.push(Place(0,0,grid[0][0]));
        while(!pq.empty()){
            Place now =pq.top();
            pq.pop();
            if(visit[now.x][now.y]) continue;
            if(now.x==m-1 && now.y==n-1)    return now.time;
            visit[now.x][now.y] = 1;		//最短的时间
            for(int i=0; i<4; i++){
                if(now.x+dir[i][0]>=0 && now.x+dir[i][0]<m && now.y+dir[i][1]>=0 && now.y+dir[i][1]<n && !visit[now.x+dir[i][0]][now.y+dir[i][1]]){
                    if(now.time >= grid[now.x+dir[i][0]][now.y+dir[i][1]]){		//当前时间超过所需时间,则以旧时间达到该地
                        pq.push(Place(now.x+dir[i][0],now.y+dir[i][1],now.time));
                    }else{		//当前时间没有超过所需时间,则以新时间达到该地
                        pq.push(Place(now.x+dir[i][0],now.y+dir[i][1],grid[now.x+dir[i][0]][now.y+dir[i][1]]));
                    }   
                }
            }
        }
        return -1;
    }
};

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swim-in-rising-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值