UVA11573 Ocean Currents

题目链接

题目

见链接。

题解

知识点:BFS。

这道题显然用BFS,但发现洋流方向会破坏时间的有序性,但注意到洋流时间花费是 0 ,因此只需要用双端队列即可,洋流方向扩展直接放队头,其他方向放队尾。

同样要注意时间线在本次就改变,因此锁点要在之后锁。

时间复杂度 O(?)

空间复杂度 O(mn)

代码

#include <bits/stdc++.h>
using namespace std;
int n, m;
char dt[57][57];
const int dir[8][2] = { {-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1} };
bool vis[57][57];
struct node {
int x, y;
int step;
};
int bfs(node st, node ed) {
deque<node> dq;
dq.emplace_back(st);
while (!dq.empty()) {
node cur = dq.front();
dq.pop_front();
if (vis[cur.x][cur.y]) continue;
vis[cur.x][cur.y] = 1;
if (cur.x == ed.x && cur.y == ed.y) return cur.step;
for (int i = 0;i < 8;i++) {
int xx = cur.x + dir[i][0];
int yy = cur.y + dir[i][1];
if (xx <= 0 || xx > n || yy <= 0 || yy > m || vis[xx][yy]) continue;
if (i == dt[cur.x][cur.y] - '0') dq.push_front({ xx,yy,cur.step });
else dq.push_back({ xx,yy,cur.step + 1 });
}
}
return -1;
}
int main() {
std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 1;i <= n;i++)
for (int j = 1;j <= m;j++)
cin >> dt[i][j];
int q;
cin >> q;
while (q--) {
memset(vis, 0, sizeof(vis));
int sx, sy, ex, ey;
cin >> sx >> sy >> ex >> ey;
cout << bfs({ sx,sy,0 }, { ex,ey,0 }) << '\n';
}
return 0;
}
posted @   空白菌  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示