题意:从0,0点出发到n-1,m-1点,路上的数字代表要在这个点额外待多少秒,求最短的路
递归输出路径即可
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 #include<queue> 7 #include<map> 8 using namespace std; 9 #define MOD 1000000007 10 const int INF=0x3f3f3f3f; 11 const double eps=1e-5; 12 #define cl(a) memset(a,0,sizeof(a)) 13 #define ts printf("***** "); 14 const int MAXN=1005; 15 int n,m,tt; 16 int sumt=0; 17 struct node 18 { 19 int x,y,t; 20 node(){} 21 node(int xx,int yy,int tt) 22 { 23 x=xx,y=yy,t=tt; 24 } 25 friend bool operator<(node a,node b) 26 { 27 return a.t>b.t; 28 } 29 }; 30 bool vis[MAXN][MAXN]; 31 int dir[MAXN][MAXN]; 32 char maze[MAXN][MAXN]; 33 int d[4][2]={0,1,1,0,-1,0,0,-1}; 34 int kk=0; 35 int outpath(int x,int y) //递归输出,从x,y出发所在的时间 36 { 37 if(x==0&&y==0) 38 { 39 int nt=1; 40 printf("%ds:(%d,%d)->",nt,x,y); 41 return nt; 42 } 43 else 44 kk=dir[x][y]; 45 int nt=outpath(x-d[kk][0],y-d[kk][1]); 46 printf("(%d,%d) ",x,y); 47 if(0<maze[x][y]-'0'&&maze[x][y]-'0'<=9) 48 { 49 int l=maze[x][y]-'0'; 50 while(l--) 51 printf("%ds:FIGHT AT (%d,%d) ",++nt,x,y); 52 } 53 if(nt==sumt) return 0; 54 printf("%ds:(%d,%d)->",++nt,x,y); 55 return nt; 56 } 57 void bfs() 58 { 59 node now,next; 60 priority_queue<node> q; 61 q.push(node(0,0,0)); 62 vis[0][0]=1; 63 while(!q.empty()) 64 { 65 now=q.top(); 66 q.pop(); 67 if(now.x==n-1&&now.y==m-1) 68 { 69 printf("It takes %d seconds to reach the target position, let me show you the way. ",now.t); 70 sumt=now.t; 71 outpath(n-1,m-1); 72 printf("FINISH "); 73 return; 74 } 75 for(int i=0;i<4;i++) 76 { 77 next.x=now.x+d[i][0]; 78 next.y=now.y+d[i][1]; 79 next.t=now.t+1; 80 if(next.x>=0&&next.y>=0&&next.x<n&&next.y<m&&!vis[next.x][next.y]&&maze[next.x][next.y]!='X') 81 { 82 if('0'<maze[next.x][next.y]&&maze[next.x][next.y]<='9') 83 { 84 next.t+=maze[next.x][next.y]-'0'; 85 vis[next.x][next.y]=1; 86 dir[next.x][next.y]=i; 87 q.push(next); 88 } 89 else 90 { 91 dir[next.x][next.y]=i; 92 vis[next.x][next.y]=1; 93 q.push(next); 94 } 95 } 96 } 97 } 98 puts("God please help our poor hero. FINISH"); 99 } 100 int main() 101 { 102 int i,j,k; 103 #ifndef ONLINE_JUDGE 104 freopen("1.in","r",stdin); 105 #endif 106 while(scanf("%d%d",&n,&m)!=EOF) 107 { 108 for(i=0;i<n;i++) 109 { 110 scanf("%s",maze[i]); 111 } 112 cl(vis); 113 bfs(); 114 } 115 }