AcWing算法提高课【第二章搜索】最短路模型
2021/4/25 12:55:08
本文主要是介绍AcWing算法提高课【第二章搜索】最短路模型,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1076. 迷宫问题
分析:
将st数组改为pair类型,记录每个格子从那一步回来,从终点反推。
代码:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 5 using namespace std; 6 7 typedef pair<int, int> PII; 8 9 #define x first 10 #define y second 11 12 const int N = 1010; 13 14 int n; 15 int g[N][N]; 16 PII q[N * N]; 17 PII pre[N][N]; 18 19 void bfs(int sx, int sy) 20 { 21 memset(pre, -1, sizeof pre); 22 int tt = 0, hh = 0; 23 q[0] = {sx, sy}; 24 pre[sx][sy] = {0, 0}; 25 26 int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; 27 while (hh <= tt) 28 { 29 PII t = q[hh ++ ]; 30 for (int i = 0; i < 4; i ++ ) 31 { 32 int x = t.x + dx[i], y = t.y + dy[i]; 33 34 if (x < 0 || x >= n || y < 0 || y >= n) continue; 35 if (g[x][y]) continue; 36 if (pre[x][y].x != -1) continue; 37 38 pre[x][y] = {t.x, t.y}; 39 q[++ tt] = {x, y}; 40 } 41 } 42 } 43 int main() 44 { 45 scanf("%d", &n); 46 for (int i = 0; i < n; i ++ ) 47 for (int j = 0; j < n; j ++ ) 48 scanf("%d", &g[i][j]); 49 50 bfs(n - 1, n - 1); 51 52 PII end(0, 0); 53 while (true) 54 { 55 printf("%d %d\n", end.x, end.y); 56 if (end.x == n - 1 && end.y == n - 1) break; 57 end = pre[end.x][end.y]; 58 } 59 return 0; 60 }View Code
这篇关于AcWing算法提高课【第二章搜索】最短路模型的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升