BFS最短路径的记录
在网上看到了一个记录BFS最短路径的方法,
个人觉得相当的牛B,所以就将它记录下来了。
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1026
这个题目比较简单,就不说题意了。
直接上代码:

#include "iostream" #include "cstring" #include "cstdio" #include "algorithm" #include "queue" using namespace std; #define MAX 1000000 typedef struct Path{ int time; int x, y; int ttime; }Path; typedef struct Point{ int x, y; }Point; int d[4][2]={{-1, 0}, {1, 0},{0, -1},{0, 1}}; Point p1, p2; int Row, Col; Path Map[105][105];//这个你想到用过吗,没有吧,就只是这个已经是很大的亮点了,也可以说是整个题目的最大亮点了 void BFS(){ queue<Point> q; Map[0][0].time = 0; p1.x = Row-1; p1.y = Col-1; Map[Row-1][Col-1].ttime = Map[Row-1][Col-1].time; q.push(p1); while(!q.empty()){ p1 = q.front(); q.pop(); if(p1.x==0 && p1.y==0) continue; for(int k=0; k<4; k++){ p2.x = p1.x+d[k][0]; p2.y = p1.y+d[k][1]; if(p2.x<0 || p2.x>Row-1 || p2.y<0 || p2.y>Col-1 || Map[p2.x][p2.y].time==-1) continue; if(Map[p1.x][p1.y].ttime+Map[p2.x][p2.y].time<Map[p2.x][p2.y].ttime){ Map[p2.x][p2.y].ttime = Map[p1.x][p1.y].ttime+Map[p2.x][p2.y].time; Map[p2.x][p2.y].x = p1.x; Map[p2.x][p2.y].y = p1.y; q.push(p2); } } } } int main(){ char ch; while(cin>>Row>>Col){ getchar(); for(int i=0; i<Row; i++){ for(int j=0; j<Col; j++){ cin>>ch; Map[i][j].ttime = MAX; if(ch=='.') Map[i][j].time = 1; else if(ch=='X') Map[i][j].time = -1; else Map[i][j].time = ch-'0'+1; } getchar(); } int i, j, k, h; BFS(); if(Map[0][0].ttime==MAX) printf("God please help our poor hero.\n"); else{ i=0;j=k=0; printf("It takes %d seconds to reach the target position, let me show you the way.\n",Map[0][0].ttime); while(i<Map[0][0].ttime){ if(Map[j][k].time>1){ while(--Map[j][k].time){ i++; printf("%ds:FIGHT AT (%d,%d)\n",i,j,k); } }else{ i++; printf("%ds:(%d,%d)->(%d,%d)\n",i,j,k,Map[j][k].x,Map[j][k].y); h=Map[j][k].x; k=Map[j][k].y; j=h; } } } printf("FINISH\n"); } }
posted on 2012-04-28 16:51 More study needed. 阅读(713) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架