广搜,碰到战斗直接往队列后面扔,打印路径递归实现
1 #include <stdio.h> 2 #include<string.h> 3 #include<queue> 4 using namespace std; 5 int n,m; 6 char map[105][105]; 7 int s[105][105]; 8 int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; 9 int fa[105][105]; 10 11 void bfs() 12 { 13 queue<int> q; 14 queue<int> hp; 15 int u=0,x,y,h; 16 s[0][0]=1; 17 fa[0][0]=0; 18 q.push(u); 19 hp.push(0); 20 while (!q.empty()) 21 { 22 u=q.front(); 23 h=hp.front(); 24 q.pop();hp.pop(); 25 x=u/m; 26 y=u%m; 27 //printf("%d %d\n",x,y); 28 if(h) 29 { 30 s[x][y]++; 31 q.push(u); 32 h--; 33 hp.push(h); 34 continue; 35 } 36 for (int i=0;i<4;i++) 37 { 38 int xx=dir[i][0]+x; 39 int yy=dir[i][1]+y; 40 if(xx>=0&&xx<n&&yy>=0&&yy<m&&map[xx][yy]!='X'&&s[xx][yy]==0) 41 { 42 if(map[xx][yy]=='.') 43 { 44 s[xx][yy]=s[x][y]+1; 45 fa[xx][yy]=x*m+y; 46 q.push(xx*m+yy); 47 hp.push(0); 48 } 49 else if(map[xx][yy]>='1'&&map[xx][yy]<='9') 50 { 51 s[xx][yy]=s[x][y]+1; 52 fa[xx][yy]=x*m+y; 53 q.push(xx*m+yy); 54 hp.push(map[xx][yy]-'0'); 55 } 56 } 57 } 58 } 59 } 60 61 void p(int x,int y,int steps) 62 { 63 if(steps==0) 64 return ; 65 int u=fa[x][y]; 66 int xx=u/m; 67 int yy=u%m; 68 int t=0; 69 70 if(map[x][y]>='1'&&map[x][y]<='9') 71 t=map[x][y]-'0'; 72 p(xx,yy,steps-1-t);//printf("现在在(%d,%d),父节点是(%d,%d)\n",xx,yy,x,y); 73 printf("%ds:(%d,%d)->(%d,%d)\n",steps-t,xx,yy,x,y); 74 for (int i=0;i<t;i++) 75 { 76 printf("%ds:FIGHT AT (%d,%d)\n",steps+1-t+i,x,y); 77 } 78 } 79 80 81 void print() 82 { 83 if(s[n-1][m-1]==0) 84 { 85 printf("God please help our poor hero.\n"); 86 } 87 else 88 { 89 printf("It takes %d seconds to reach the target position, let me show you the way.\n",s[n-1][m-1]-1); 90 p(n-1,m-1,s[n-1][m-1]-1); 91 } 92 printf("FINISH\n"); 93 } 94 95 int main(int argc, char *argv[]) 96 { 97 while (scanf("%d %d",&n,&m)!=EOF) 98 { 99 int i; 100 for (i=0;i<n;i++) 101 { 102 scanf("%s",map[i]); 103 } 104 memset(s,0,sizeof(s)); 105 bfs(); 106 print(); 107 //printf("%d\n",s[n-1][m-1]); 108 } 109 return 0; 110 }