标签:1631 Google ny int pq heights nx vis Minimum
You are a hiker preparing for an upcoming hike. You are given heights
, a 2D array of size rows x columns
, where heights[row][col]
represents the height of cell (row, col). You are situated in the top-left cell, (0, 0)
, and you hope to travel to the bottom-right cell, (rows-1
, columns-1
) (i.e., 0
-indexed). You can move up
, down
, left
, or right
, and you wish to find a route that requires the minimum effort.
A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
Solution
求最短路径,且路径长度是该路径中最大的高度差的绝对值。我们用 \(priority\_queue\), 数组 \(vis[i][j]\) 用来存储从原点到 \(i,j\) 的最短距离。所以在更新时:
\[vis[nx][ny]=\max(vis[x][y], |h[x][y]-h[nx][ny]|) \]然后将新的点 \(push\) 到优先队列里面
点击查看代码
class Solution {
private:
int dir[4][2] = {
1,0,
0,1,
-1,0,
0,-1
};
priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>> > pq;
vector<vector<int>> vis;
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 minimumEffortPath(vector<vector<int>>& heights) {
int r = heights.size(), c = heights[0].size();
vis = vector<vector<int>>(r, vector<int>(c,INT_MAX));
pq.push({0,0,0});
vis[0][0]=0;
while(!pq.empty()){
auto f = pq.top();pq.pop();
int x = f[1], y = f[2];
int sp = f[0];
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]>max(sp,abs(heights[x][y]-heights[nx][ny]))){
vis[nx][ny] = max(sp, abs(heights[x][y]-heights[nx][ny]));
pq.push({vis[nx][ny],nx,ny});
}
}
}
return vis[r-1][c-1];
}
};
标签:1631,Google,ny,int,pq,heights,nx,vis,Minimum 来源: https://www.cnblogs.com/xinyu04/p/16671371.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。