ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-09-02 23:05:23  阅读:161  来源: 互联网

标签:Swim swim Google return int 778 square grid ans


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;
    }
};








标签:Swim,swim,Google,return,int,778,square,grid,ans
来源: https://www.cnblogs.com/xinyu04/p/16651570.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有