题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1026
这题本来想着看大牛博客如何在搜索中记录路径,但是突然间最近刚刷的spfa记录路径给了灵感。由于spfa本质就是BFS,所以可以采用SPFA记录路径的方法。但是这里的路径是二维的,不好记录,于是想到了个方法是把二维转化成一维用来保存,当输出的时候再转化成二维路径。于是试了一下,还真成功了。见代码:
#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <queue> #include <map> #include<algorithm> using namespace std; int n, m, vis[200][200], pre[10002],lu[10002]; char mp[200][200]; int jx[]={0,0,1,-1}; int jy[]={1,-1,0,0}; struct node { int x, y, z, ans; }; int bfs() { int i, j; queue<node>q; node f1, f2; f1.x=0; f1.y=0; f1.z=0; if(mp[0][0]>='1'&&mp[0][0]<='9') f1.z=mp[0][0]-'0'; f1.ans=0; q.push(f1); vis[0][0]=1; while(!q.empty()) { f1=q.front(); q.pop(); if(f1.x==n-1&&f1.y==m-1&&f1.z==0) { printf("It takes %d seconds to reach the target position, let me show you the way.\n",f1.ans); return 1; } if(f1.z>0) { f2.x=f1.x; f2.y=f1.y; f2.z=f1.z-1; f2.ans=f1.ans+1; q.push(f2); continue ; } for(i=0;i<4;i++) { f2.x=f1.x+jx[i]; f2.y=f1.y+jy[i]; if(f2.x>=0&&f2.x<n&&f2.y>=0&&f2.y<m&&!vis[f2.x][f2.y]&&mp[f2.x][f2.y]=='.') { f2.z=0; f2.ans=f1.ans+1; vis[f2.x][f2.y]=1; pre[m*f2.x+f2.y]=m*f1.x+f1.y; q.push(f2); } if(f2.x>=0&&f2.x<n&&f2.y>=0&&f2.y<m&&!vis[f2.x][f2.y]&&mp[f2.x][f2.y]>='1'&&mp[f2.x][f2.y]<='9') { f2.z=mp[f2.x][f2.y]-'0'; f2.ans=f1.ans+1; vis[f2.x][f2.y]=1; pre[m*f2.x+f2.y]=m*f1.x+f1.y; q.push(f2); } } } printf("God please help our poor hero.\n"); return 0; } int main() { int i, j, x, cnt, y; while(scanf("%d%d",&n,&m)!=EOF) { memset(vis,0,sizeof(vis)); for(i=0;i<n;i++) { scanf("%s",mp[i]); } x=bfs(); if(x) { cnt=0; j=1; for(i=n*m-1;i!=0;i=pre[i]) { lu[cnt++]=i; } /*for(i=0;i<cnt;i++) printf("%d %d\n",lu[i]/m,lu[i]%m);*/ if(mp[0][0]>='0'&&mp[0][0]<='9') { y=mp[0][0]-'0'; while(y--) { printf("%ds:FIGHT AT (0,0)\n",j++); } } printf("%ds:(0,0)->(%d,%d)\n",j++,lu[cnt-1]/m,lu[cnt-1]%m); if(mp[lu[cnt-1]/m][lu[cnt-1]%m]>='0'&&mp[lu[cnt-1]/m][lu[cnt-1]%m]<='9') { y=mp[lu[cnt-1]/m][lu[cnt-1]%m]-'0'; //printf("%d\n",y); while(y--) { printf("%ds:FIGHT AT (%d,%d)\n",j++,lu[cnt-1]/m,lu[cnt-1]%m); } } for(i=cnt-2;i>=0;i--) { printf("%ds:(%d,%d)->(%d,%d)\n",j++,lu[i+1]/m,lu[i+1]%m,lu[i]/m,lu[i]%m); if(mp[lu[i]/m][lu[i]%m]>='0'&&mp[lu[i]/m][lu[i]%m]<='9') { y=mp[lu[i]/m][lu[i]%m]-'0'; //printf("%d\n",y); while(y--) { printf("%ds:FIGHT AT (%d,%d)\n",j++,lu[i]/m,lu[i]%m); } } } } printf("FINISH\n"); } return 0; }