hdu 1026 Ignatius and the Princess I(BFS)
2013-11-22 12:33
537 查看
只需要记录路径就行了,对于花费的时间,可以用优先队列来维护。难得的1A。
#include<stdio.h> #include<string.h> #include<queue> using namespace std; #define N 105 int mark ,vis ; int n,m; char s ; int cnt; int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}}; struct node { int x,y; int cnt; friend bool operator<(node a,node b) { return a.cnt>b.cnt; }; }q[N*N]; struct point { int prex,prey; }ans ; int judge(int x,int y) { if(x>=1&&x<=m&&y>=1&&y<=n&&mark[x][y]!=-1&&vis[x][y]==0) return 1; return 0; } int BFS() { node cur,next; cur.x=1;cur.y=1;cur.cnt=0;vis[1][1]=1; priority_queue<node>q; q.push(cur); while(!q.empty()) { cur=q.top(); q.pop(); for(int i=0;i<4;i++) { next.cnt=cur.cnt+1; next.x=cur.x+dir[i][0]; next.y=cur.y+dir[i][1]; if(judge(next.x,next.y)) { if(mark[next.x][next.y]!=0) next.cnt+=mark[next.x][next.y]; vis[next.x][next.y]=1; ans[next.x][next.y].prex=cur.x;ans[next.x][next.y].prey=cur.y; if(next.x==m&&next.y==n) return next.cnt; q.push(next); } } } return -1; } void print(int x,int y) { if(x==1&&y==1) return ; print(ans[x][y].prex,ans[x][y].prey); printf("%ds:(%d,%d)->(%d,%d)\n",cnt++,ans[x][y].prex-1,ans[x][y].prey-1,x-1,y-1); if(mark[x][y]==0) return ; while(mark[x][y]--) printf("%ds:FIGHT AT (%d,%d)\n",cnt++,x-1,y-1); return ; } int main() { while(scanf("%d%d",&m,&n)!=EOF) { getchar(); for(int i=1;i<=m;i++) { gets(s+1); for(int j=1;j<=n;j++) { if(s[j]=='.') mark[i][j]=0; else if(s[j]=='X') mark[i][j]=-1; else mark[i][j]=s[j]-'0'; } } int answer; memset(vis,0,sizeof(vis)); memset(ans,0,sizeof(ans)); answer=BFS(); if(answer==-1) printf("God please help our poor hero.\n"); else { printf("It takes %d seconds to reach the target position, let me show you the way.\n",answer); cnt=1; print(m,n); } printf("FINISH\n"); } return 0; }
相关文章推荐
- hdu 1026 Ignatius and the Princess I bfs
- HDU 1026 Ignatius and the Princess I(BFS+记录路径)
- hdu1026 Ignatius and the Princess I BFS
- HDU 1026 Ignatius and the Princess I 【BFS(优先队列)+路径存储】
- hdu 1026:Ignatius and the Princess I(优先队列 + bfs广搜。ps:广搜AC,深搜超时,求助攻!)
- hdu 1026(Ignatius and the Princess I)BFS
- HDU 1026 Ignatius and the Princess I && BFS+记录路径
- HDU杭电1026 Ignatius and the Princess I(迷宫问题bfs)
- hdu 1026 Ignatius and the Princess I BFS
- Ignatius and the Princess I hdu 1026 priority_queue + bfs (vector)
- hdu 1026 Ignatius and the Princess I (bfs打印路径)
- 【Bfs】HDU 1026 Ignatius and the Princess I
- 我爱崔老师系列之 BFS+优先队列+路径记录 HDU 1026 Ignatius and the Princess I(BFS)
- hdu 1026 Ignatius and the Princess I(bfs+priority_queue)
- HDU 1026 Ignatius and the Princess I(优先队列bfs)
- hdu 1026 Ignatius and the Princess I (bfs)
- hdu1026 Ignatius and the Princess I (优先队列 BFS)
- hdu 1026 Ignatius and the Princess I(bfs)
- HDU 1026 Ignatius and the Princess I (BFS+记录路径)
- HDU 1026 Ignatius and the Princess I (BFS输出路径)