算法题解---双向队列的优化
题目
思路
主要是将优先级较高的放在队列前面,提前出队,优先级低的放在队列尾处。
如何判断优先级将是至关重要的
- 如果路过该点会使的之后的答案与题目要求相违背
- 即该点优先级较低,可以放入队尾
- 反之,可以放入队头
代码
queue未优化#
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
typedef pair<int,int> pii;
class Solution {
public:
int minimumObstacles(vector<vector<int>>& grid) {
auto & g = grid;
int m = g.size();
int n= g[0].size();
vector<vector<int> > st(m+10,vector<int>(n+10,0x3f3f3f3f));
queue<pii> heap;
heap.push({0,0});
int cnt=0;
if(g[0][0])cnt++;st[0][0]=0;
while(heap.size()){
auto top = heap.front();
heap.pop();
for(int i=0;i<4;i++){
int x= top.first+dx[i],y=top.second+dy[i];
if(x<0||x>=m||y<0||y>=n||st[x][y]<=(st[top.first][top.second]+g[x][y]))continue;
st[x][y]=st[top.first][top.second]+g[x][y];
heap.push({x,y});
}
}
// for(int i=0;i<m;i++){
// for(int j=0;j<n;j++){
// cout<<st[i][j]<<" ";
// }cout<<endl;
// }
return cnt+st[m-1][n-1];
}
};
deque优化#
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
typedef pair<int,int> pii;
class Solution {
public:
int minimumObstacles(vector<vector<int>>& grid) {
auto & g = grid;
int m = g.size();
int n= g[0].size();
vector<vector<int> > st(m+10,vector<int>(n+10,0x3f3f3f3f));
deque<pii> heap;
heap.push_front({0,0});
int cnt=0;
if(g[0][0])cnt++;st[0][0]=0;
while(heap.size()){
auto top = heap.front();
heap.pop_front();
for(int i=0;i<4;i++){
int x= top.first+dx[i],y=top.second+dy[i];
if(x<0||x>=m||y<0||y>=n||st[x][y]<=(st[top.first][top.second]+g[x][y]))continue;
st[x][y]=st[top.first][top.second]+g[x][y];
if(g[x][y]) heap.push_back({x,y});
else heap.push_front({x,y});
}
}
// for(int i=0;i<m;i++){
// for(int j=0;j<n;j++){
// cout<<st[i][j]<<" ";
// }cout<<endl;
// }
return cnt+st[m-1][n-1];
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)