UVA11573 Ocean Currents
题目
见链接。
题解
知识点:BFS。
这道题显然用BFS,但发现洋流方向会破坏时间的有序性,但注意到洋流时间花费是 ,因此只需要用双端队列即可,洋流方向扩展直接放队头,其他方向放队尾。
同样要注意时间线在本次就改变,因此锁点要在之后锁。
时间复杂度
空间复杂度
代码
#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; }
本文来自博客园,作者:空白菌,转载请注明原文链接:https://www.cnblogs.com/BlankYang/p/16484846.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧