杭电1026
题意:从地图左上角走到地图右下角所需的最短时间及路径。
Analyse:用BFS,但是每个点所需的时间不同,因此BFS要改动。把地图上到达每个点的时间先初始化为INF,判断要不要从所在点走向下一点,若下一点的时间比这一点到下一点的时间长,则更新到达下一点的时间,下一点不管之前有没有遍历过都要放进队列里。
如果把右下角作为起点,左上角作为终点,记录的路径就容易回溯得到了。
View Code
1 #include<cstdio> 2 #include<queue> 3 using namespace std; 4 typedef struct 5 { 6 int x; 7 int y; 8 }point; 9 typedef struct 10 { 11 point prep; 12 int cost; 13 int time; 14 }map; 15 const int INF=10000000; 16 point p1,p2; 17 map mp[102][102]; 18 int n,m; 19 int dir[4][2]={-1,0,0,-1,1,0,0,1}; 20 char c; 21 bool inborder(int x,int y) 22 { 23 return x>=0 && x<n && y>=0 && y<m; 24 } 25 int cost_time(const char c) 26 { 27 if(c=='X') 28 return INF; 29 if(c=='.') 30 return 1; 31 return (c-'0'+1); 32 } 33 void bfs() 34 { 35 queue<point> q; 36 int i; 37 p1.x=n-1; 38 p1.y=m-1; 39 q.push(p1); 40 while(!q.empty()) 41 { 42 p1=q.front(); 43 q.pop(); 44 if(p1.x==0 && p1.y==0) 45 continue; 46 for(i=0;i<4;i++) 47 { 48 p2.x=dir[i][0]+p1.x; 49 p2.y=dir[i][1]+p1.y; 50 if(inborder(p2.x,p2.y)) 51 { 52 if(mp[p1.x][p1.y].time+mp[p2.x][p2.y].cost<mp[p2.x][p2.y].time) 53 { 54 mp[p2.x][p2.y].time=mp[p1.x][p1.y].time+mp[p2.x][p2.y].cost; 55 mp[p2.x][p2.y].prep=p1; 56 q.push(p2); 57 } 58 } 59 } 60 } 61 } 62 int main() 63 { 64 int i,j; 65 while(~scanf("%d%d",&n,&m)) 66 { 67 for(i=0;i<n;i++) 68 { 69 getchar(); 70 for(j=0;j<m;j++) 71 { 72 scanf("%c",&c); 73 mp[i][j].cost=cost_time(c); 74 mp[i][j].time=INF; 75 } 76 } 77 mp[n-1][m-1].time=mp[n-1][m-1].cost-1; 78 mp[n-1][m-1].cost--; 79 bfs(); 80 if(mp[0][0].time!=INF) 81 { 82 printf("It takes %d seconds to reach the target position, let me show you the way.\n",mp[0][0].time); 83 p1.x=p1.y=0; 84 for(i=1;i<=mp[0][0].time-mp[n-1][m-1].cost;i++) 85 { 86 printf("%ds:",i); 87 if(mp[p1.x][p1.y].cost==1) 88 { 89 p2=mp[p1.x][p1.y].prep; 90 printf("(%d,%d)->(%d,%d)\n",p1.x,p1.y,p2.x,p2.y); 91 p1=mp[p1.x][p1.y].prep; 92 } 93 else if(mp[p1.x][p1.y].cost>1) 94 { 95 mp[p1.x][p1.y].cost--; 96 printf("FIGHT AT (%d,%d)\n",p1.x,p1.y); 97 } 98 } 99 for(;i<=mp[0][0].time;i++) 100 { 101 printf("%ds:",i); 102 printf("FIGHT AT (%d,%d)\n",p1.x,p1.y); 103 } 104 } 105 else 106 printf("God please help our poor hero.\n"); 107 printf("FINISH\n"); 108 } 109 return 0; 110 }


浙公网安备 33010602011771号