/* hdu 1026 bfs+優先隊列+記錄路徑 記錄路徑的時候要注意*/#include <cstdio>#include <queue>#include <cstring>using namespace std;#define maxn 105int n,m;int dir[4][2]={{-1,0},{0,1},{0,-1},{1,0}}; //走路的方向不要錯,不能寫成{{-1,0}{1,0},{0,-1},{0,1}},struct Node //因為要記錄路徑 不能走了左邊之後又從右邊走 這就回到了之前的位置{ int x,y; int step; friend bool operator <(Node a,Node b) { return a.step>b.step; }};char map[maxn][maxn];Node start,end,cut,next;int h[maxn][maxn];int mark[maxn][maxn];int bfs(Node s){ memset(mark,0,sizeof(mark)); memset(h,0,sizeof(h)); priority_queue<Node>q; q.push(s); while(!q.empty()) { Node cut; cut=q.top();// road[cut.step].x=cut.x,road[cut.step].y=cut.y; // if(markx[cut.x] && marky[cut.y]) road[cut.st] q.pop();// printf("cut:%d %d %d\n",cut.x,cut.y,cut.step); for(int i=0; i<4; i++) {// printf("cut:%d %d %d\n",cut.x,cut.y,cut.step); next.x=cut.x+dir[i][0]; next.y=cut.y+dir[i][1]; if( map[next.x][next.y]!='X') if(next.x>=0 && next.x<n && next.y>=0 && next.y<m ) { mark[next.x][next.y]=i+1; //記錄路徑// printf("x:%d y:%d mark:%d\n",next.x,next.y,mark[next.x][next.y]); // printf("%c x:%d y:%d step:%d\n",map[next.x][next.y],next.x,next.y,next.step); if(map[next.x][next.y]=='.' && (next.x!=n-1 || next.y!=m-1)) map[next.x][next.y]='X', next.step=cut.step+1; else if(map[next.x][next.y]>='1' && map[next.x][next.y]<='9') { h[next.x][next.y]=map[next.x][next.y]-'0'; if(next.x==n-1 && next.y==m-1) { end.step=cut.step+(map[next.x][next.y]-'0')+1;return 1;} next.step=cut.step+(map[next.x][next.y]-'0')+1, map[next.x][next.y]='X'; } else if(next.x==n-1 && next.y==m-1) { end.step=cut.step+1;return 1;} // printf("after:%d %d %d \n",next.x,next.y,next.step); q.push(next); }// printf("das\n");// while(1){} } } return 0;}int temp;void Print(int a,int b){ int u,v; if(mark[a][b]==0) return; u=a-dir[mark[a][b]-1][0]; v=b-dir[mark[a][b]-1][1];// printf("u:%d v:%d \n",u,v);// while(1){} Print(u,v); printf("%ds:(%d,%d)->(%d,%d)\n",temp++,u,v,a,b); while(h[a][b]--) {printf("%ds:FIGHT AT (%d,%d)\n",temp++,a,b);}}int main(){ while(scanf("%d%d",&n,&m)!=EOF) { int wall=0; char str[maxn]; for(int i=0; i<n; i++) { scanf("%s",str); for(int j=0; j<m; j++) { map[i][j]=str[j]; if(map[i][j]=='X') wall++; } }// for(int i=0; i<n; i++)// printf("%sprintf("(%d,%d)->(%d,%d)\n",road[i-1].x,road[i-1].y,road[i].x,road[i].y);",map[i]);// if(n*m-wall<m+n-1)// {// printf("God please help our poor hero.\nFINISH");// continue;// } start.x=0,start.y=0,start.step=0; map[0][0]='X'; if(!bfs(start)) { printf("God please help our poor hero.\nFINISH\n"); //WA的時候是FINISH後面沒有空行!~沒有提示PE,烏龍~~~ continue; } else { printf("It takes %d seconds to reach the target position, let me show you the way.\n",end.step); temp=1; Print(n-1,m-1); } printf("FINISH\n"); }}