hdu1026 BFS+记录路径
来源:互联网 发布:模拟短信发送 java 编辑:程序博客网 时间:2024/05/22 10:47
http://acm.hdu.edu.cn/showproblem.php?pid=1026
用的普通的队列
由于一些点打怪物要占据一定的时间,要注意进队条件,(最基本的广搜只是层次遍历,每次取队头,然后其相邻的点进队,同时已经进队的做标记,是不可取的)如果某一点能提供一条更短的路则进队,所以某些点不止搜索了一次
#include <iostream>#include<cstdio>#include<cstring>#include<queue>using namespace std;#define MAX 105#define INF 0x3f3f3f3fchar map[MAX][MAX];int n,m,t[MAX][MAX],fa[MAX][MAX];int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};typedef struct{ int x,y;}Node;void bfs(){ queue<Node>q; Node node={0,0}; q.push(node); while(!q.empty()) { node=q.front(); q.pop(); int x=node.x; int y=node.y; for(int i=0;i<4;i++) { int tx=x+dx[i]; int ty=y+dy[i]; if(tx>=0&&tx<n&&ty>=0&&ty<m&&map[tx][ty]=='.') { if(t[tx][ty]>t[x][y]+1) { t[tx][ty]=t[x][y]+1; fa[tx][ty]=i;//记录如何由上一点找到该点的 node.x=tx; node.y=ty; q.push(node); } } if(tx>=0&&tx<n&&ty>=0&&ty<m&&map[tx][ty]>='1'&&map[tx][ty]<='9') { int k=map[tx][ty]-'0'; if(t[tx][ty]>t[x][y]+k+1) { t[tx][ty]=t[x][y]+k+1; fa[tx][ty]=i; node.x=tx; node.y=ty; q.push(node); } } } }}int main(){ int i; while(scanf("%d%d",&n,&m)!=EOF) { for(i=0;i<n;i++) { scanf("%s",map[i]);//图 } memset(t,INF,sizeof(t));//初始化时间 t[0][0]=0; bfs(); /*for(i=0;i<n;i++) { for(int j=0;j<m;j++) cout<<t[i][j]<<" "; cout<<endl; } cout<<endl;*/ if(t[n-1][m-1]==INF)//无法到终点 { cout<<"God please help our poor hero."<<endl<<"FINISH"<<endl; continue; } printf("It takes %d seconds to reach the target position, let me show you the way.\n",t[n-1][m-1]); int x=n-1,y=m-1,trace[MAX*MAX][2],c=2; trace[1][0]=x,trace[1][1]=y; while(!(x==0&&y==0))//由终点开始逆向存储路径,trace中最后一个是起点 { i=fa[x][y]; int fx=x-dx[i];//父亲点 int fy=y-dy[i]; trace[c][0]=fx; trace[c++][1]=fy; x=fx;y=fy; } int k=1; for(i=c-1;i>=1;i--)//由起点开始到终点,要循环到终点,因为终点可能有怪物,有FIGHT时间 { x=trace[i][0],y=trace[i][1]; if(map[x][y]>='1'&&map[x][y]<='9') { int tt=map[x][y]-'0'; for(int j=1;j<=tt;j++) { printf("%ds:FIGHT AT (%d,%d)\n",k++,x,y); } } if(i!=1) printf("%ds:(%d,%d)->(%d,%d)\n",k++,trace[i][0],trace[i][1],trace[i-1][0],trace[i-1][1]); } cout<<"FINISH"<<endl; } return 0;}
测试数据
5 7
...X...
.X.X.X.
.X...X.
.XXXXX.
....9..
- hdu1026 BFS+记录路径
- hdu1026 bfs+记录路径
- HDU1026(BFS求最短路径并记录)
- hdu1026 BFS+路径保存
- HDU1026 Ignatius and the Princess I 【BFS】+【路径记录】
- hdu1026 Ignatius and the Princess I(BFS+路径记录)
- hdu1026(BFS,打印路径)
- hdu1026 Ignatius and the Princess I --BFS & 记录路径 & 与DFS的比较
- hdu1026 Ignatius and the Princess I(bfs+优先队列+记录路径)
- HDU1026 BFS&&优先队列&&路径保存
- hdu1026(bfs + priority_queue + 寻找路径)
- hdu1026(bfs+dfs打印路径)
- hdu1026 bfs
- hdu1026 Ignatius and the Princess I bfs 路径保存
- hdu1026 Ignatius and the Princess I(bfs+路径)
- hdu1026 Ignatius and the Princess I(广搜+记录路径)
- hdu1026(bfs+优先级队列)
- HDU1026 bfs+优先队列
- 堆排序
- 黑马程序员--java反射
- [资源分享]Linode主机控制台介绍(篇一) [ 资源分享 ]
- Hdu 1233 - 还是通畅工程
- [资源分享]Linode主机控制台介绍(篇二) [ 资源分享 ]
- hdu1026 BFS+记录路径
- [Windows] Windows 2003 安装终端服务 [ 技术分享 ]
- 三节点RAC 调优前后比对(续)
- main already defined in *.obj 解决方法
- php入门交流:鼓舞学习PHP的新手
- 希尔排序算法知识总结
- 细数PHP顺序的一些缺陷
- char 与 u_char类型指针
- 菜鸟学JDBC(一)