hdu 1026
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1026
给出起始点和目的点,问如何用最少的时间到达,并输出路径,如果一个点是个数字 t ,表示必须在这个点逗留 t 秒,
View Code
1 const int N = 110; 2 char map[N][N]; 3 int vis[N][N]; 4 int n,m; 5 int sum; 6 int move[4][2] = {{1,0},{-1,0},{0,-1},{0,1}}; 7 struct node 8 { 9 int x,y; 10 int tim; 11 int px,py; 12 }s,e,path[N][N]; 13 int juge(int x,int y) 14 { 15 if(x >= 0 && x < n && y >= 0 && y < m && map[x][y] != 'X') 16 return 1; 17 else return 0; 18 } 19 void bfs() 20 { 21 queue<node>qu; 22 node t,k; 23 int i,j; 24 qu.push(s); 25 while(!qu.empty()) 26 { 27 t = qu.front(); 28 qu.pop(); 29 for(i = 0;i < 4; i++) 30 { 31 k.x = t.x + move[i][0]; 32 k.y = t.y + move[i][1]; 33 if(juge(k.x,k.y)) 34 { 35 if(map[k.x][k.y] == '.') k.tim = t.tim + 1; 36 else k.tim = t.tim + map[k.x][k.y] - '0' + 1; // 每跳一步都需要 1 秒 37 if(k.tim < path[k.x][k.y].tim || path[k.x][k.y].tim == -1) 38 { 39 k.px = t.x, k.py = t.y; 40 path[k.x][k.y] = k; 41 qu.push(k); 42 } 43 } 44 } 45 } 46 } 47 int main() 48 { 49 int i,j; 50 //freopen("data.txt","r",stdin); 51 while(~scanf("%d%d",&n,&m)) 52 { 53 for(i = 0; i < n; i++) 54 { 55 for(j = 0; j < m; j++) 56 path[i][j].tim = -1; 57 } 58 for(i = 0; i < n; i++) 59 cin>>map[i]; 60 s.x = s.y = s.px = s.py = s.tim = 0; 61 bfs(); 62 if(path[n - 1][m - 1].tim == -1) {printf("God please help our poor hero.\nFINISH\n");continue;} 63 e = path[n - 1][m - 1]; 64 stack<node>st; 65 while(1) 66 { 67 if(e.x == 0 && e.y == 0) break; 68 st.push(e); 69 e = path[e.px][e.py]; 70 } 71 printf("It takes %d seconds to reach the target position, let me show you the way.\n",path[n - 1][m - 1].tim); 72 int ttim = 0; 73 while(!st.empty()) 74 { 75 node tem = st.top(); 76 st.pop(); 77 if(map[tem.x][tem.y] == '.') printf("%ds:(%d,%d)->(%d,%d)\n",++ttim,e.x,e.y,tem.x,tem.y); 78 else 79 { 80 printf("%ds:(%d,%d)->(%d,%d)\n",++ttim,e.x,e.y,tem.x,tem.y); 81 int kem = map[tem.x][tem.y] - '0'; 82 while(kem--){printf("%ds:FIGHT AT (%d,%d)\n",++ttim,tem.x,tem.y);} 83 } 84 e = tem; 85 } 86 printf("FINISH\n"); 87 } 88 return 0; 89 }