[Google] LeetCode 778 Swim in Rising Water 优先队列

2022/9/2 23:52:58

本文主要是介绍[Google] LeetCode 778 Swim in Rising Water 优先队列,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).

The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.

Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).

Solution

注意到水的深度和时间 \(t\) 一样。且可以在相同的高度游到任何地方。所以我们只在意最小的最大高度。比如在下游的位置的高度比上游的高度低,那么我们可以直接游到那里,但是时间不变。

所以,我们可以利用 \(priority\_queue\) 来维护过程中的最大值

点击查看代码
class Solution {
private:
    int vis[51][51];
    int ans=0;
    priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>> >q;
    int dir[4][2]={
        1,0,
        0,1,
        -1,0,
        0,-1
    };
    
    bool check(int x,int y,int r,int c){
        if(x<0||y<0||x>=r||y>=c) return false;
        return true;
    }
    
public:
    int swimInWater(vector<vector<int>>& grid) {
        int r = grid.size(), c = grid[0].size();
        q.push({grid[0][0], 0,0});
        while(!q.empty()){
            auto f = q.top();q.pop();
            int curt = f[0];
            int x = f[1], y = f[2];
            ans = max(ans, curt);
            if(x==r-1 && y==c-1)return ans;
            
            vis[x][y]=1;
            for(int i=0;i<4;i++){
                int nx = x+dir[i][0];
                int ny = y+dir[i][1];
                if(check(nx,ny,r,c) && !vis[nx][ny]){
                    q.push({grid[nx][ny], nx,ny});
                }
            }
        }
        return -1;
    }
};










这篇关于[Google] LeetCode 778 Swim in Rising Water 优先队列的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程