#include <stdio.h> #include <string.h> #include <queue> #include <stack> using namespace std; #define M 105 typedef struct Node{ int row,col,step,f_row,f_col,count; friend bool operator < (const Node a,const Node b) { return a.step>b.step; } } Node; const int move[4][2]={{-1,0},{1,0},{0,-1},{0,1}}; char map[M][M]; int n,m,sum; priority_queue<Node> Q; queue<Node> __Q; stack<Node> S,__S; void __clear() { while(!Q.empty()) Q.pop(); while(!S.empty()) S.pop(); while(!__Q.empty()) __Q.pop(); while(!__S.empty()) __S.pop(); } int jud(Node temp) { if(temp.row>=0 && temp.row<n && temp.col>=0 && temp.col<m && map[temp.row][temp.col]!='X') return 1; return 0; } void bfs() { __clear(); Node temp,add; temp.row=temp.col=temp.step=0; temp.f_row=temp.f_col=-1; temp.count=0; map[temp.row][temp.col]='X'; Q.push(temp); while(!Q.empty()) { temp=Q.top(); Q.pop(); __Q.push(temp); if(temp.row==n-1 && temp.col==m-1) { sum=temp.step; return ; } for(int i=0;i<4;i++) { add.row=temp.row+move[i][0]; add.col=temp.col+move[i][1]; add.f_row=temp.row; add.f_col=temp.col; if(!jud(add)) continue; add.step=temp.step+1; add.count=0; if(map[add.row][add.col]!='.') { add.step=add.step+map[add.row][add.col]-'0'; add.count=map[add.row][add.col]-'0'; } map[add.row][add.col]='X'; Q.push(add); } } } void show_path() { while(!__Q.empty()) { S.push(__Q.front()); __Q.pop(); } int __f_row=S.top().row; int __f_col=S.top().col; while(!S.empty()) { Node temp=S.top(); S.pop(); if(!(__f_row ==temp.row && __f_col ==temp.col)) continue; __f_row=temp.f_row; __f_col=temp.f_col; __S.push(temp); } int i=1; if(sum) printf("It takes %d seconds to reach the target position, let me show you the way.\n",sum); else { printf("God please help our poor hero.\nFINISH\n"); return ; } while(!__S.empty()) { Node temp=__S.top(); __S.pop(); if(temp.f_row==-1 && temp.f_col==-1) continue; printf("%ds:(%d,%d)->(%d,%d)\n",i++,temp.f_row,temp.f_col,temp.row,temp.col); if(temp.count) while(temp.count--) printf("%ds:FIGHT AT (%d,%d)\n",i++,temp.row,temp.col); // printf("row=%d,col=%d,step=%d,f_row=%d,f_col=%d\n",temp.row,temp.col,temp.step,temp.f_row,temp.f_col); } printf("FINISH\n"); } int main(int argc, char *argv[]) { #ifdef __LOCAL freopen("in.txt","r",stdin); #endif while(scanf("%d%d",&n,&m)!=EOF) { for(int i=0;i<n;i++) scanf("%s",map[i]); sum=0; bfs(); show_path(); } return 0; }