hdu 1026 Ignatius and the Princess (广度优先搜索+路径打印)
Problem link adress: http://acm.hdu.edu.cn/showproblem.php?pid=1026
这个题目很早就见了,只是碍于没有打印BFS路径的经验就放到了今天!下面先写一种用记录前驱路径的打印方法。
本文仅描述打印路径的部分,BFS就略了。
实现过程:从出口向入口进行搜索,并记录下每个位置的前一个位置信息(即把当前的位置和前一个位置联系起来),这样就穿成了一条从头到尾的路径。
比如 从1搜到10,我们可以考虑从10搜到1,当搜索到9的时候,记录下9的前一个位置即10,这样依次向前直到1;
然后输出的时候就可以先输出1,然后输出1的前一个标记点即2,然后输出2的前一个标记点即3,直到10,这样一条完整的路径就打印出来了。

1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<queue> 5 using namespace std; 6 #define N 105 7 struct node{ 8 friend bool operator<(node a,node b) 9 { 10 return a.time>b.time; 11 }; 12 int x,y,time; 13 }; 14 15 struct A{ 16 int x,y; 17 }s[N][N];//记录map[i][j]前一步的位置 18 19 int n,m; 20 int mark[N][N]; 21 char map[N][N]; 22 int dir[4][2]={0,1,0,-1,1,0,-1,0}; 23 void BFS() 24 { 25 node cur,next; 26 memset(mark,0,sizeof(mark)); 27 int x,y,i; 28 priority_queue<node>q; 29 cur.x=n-1;cur.y=m-1;cur.time=0; 30 s[n-1][m-1].x=-1;//标记路口 31 mark[n-1][m-1]=1; 32 if(map[n-1][m-1]!='.')//注意这里如果出口有怪兽 33 cur.time=map[n-1][m-1]-'0'; 34 q.push(cur); 35 while(!q.empty()) 36 { 37 cur=q.top(); 38 q.pop(); 39 if(cur.x==0&&cur.y==0)//这里是采用的从出口向入口遍历的方法 所以如果遍历到入口就输出路径 40 { 41 printf("It takes %d seconds to reach the target position, let me show you the way.\n",cur.time); 42 int k=1; 43 int a=cur.x;//a,b表示当前位置坐标 44 int b=cur.y; 45 while(s[a][b].x!=-1)//前面已经特意标记过的 这里用来循环弹出条件 46 { 47 int c=s[a][b].x;//c、d表示当前坐标的前一个位置 48 int d=s[a][b].y; 49 printf("%ds:(%d,%d)->(%d,%d)\n",k++,a,b,c,d); 50 if(map[c][d]!='.')//如果有怪,输出打怪时间 51 { 52 for(int kk=0;kk<map[c][d]-'0';kk++) 53 printf("%ds:FIGHT AT (%d,%d)\n",k++,c,d); 54 } 55 a=c;b=d; 56 } 57 printf("FINISH\n"); 58 return ; 59 } 60 61 62 for(i=0;i<4;i++) 63 { 64 next.x=x=cur.x+dir[i][0]; 65 next.y=y=cur.y+dir[i][1]; 66 if(x>=0&&x<n&&y>=0&&y<m&&mark[x][y]==0&&map[x][y]!='X') 67 { 68 if(map[x][y]=='.') 69 next.time=cur.time+1; 70 else 71 next.time=cur.time+map[x][y]-'0'+1; 72 q.push(next); 73 mark[x][y]=1; 74 s[x][y].x=cur.x;//记录当前位置的前一个位置 75 s[x][y].y=cur.y; 76 } 77 } 78 } 79 80 printf("God please help our poor hero.\nFINISH\n"); 81 } 82 83 84 int main() 85 { 86 while(scanf("%d%d",&n,&m)!=EOF) 87 { 88 getchar(); 89 int i; 90 memset(s,0,sizeof(s)); 91 92 for(i=0;i<n;i++) 93 cin>>map[i]; 94 BFS(); 95 } 96 return 0; 97 }
分类:
bfs/gfs
标签:
hdu bfs 路径打印
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?