Time Limit:1000MS | Memory Limit:65536KB | 64bit IO Format:%I64d & %I64u |
[Submit] [Go Back] [Status]
Description
Input
Output
Escaped in x minute(s).
Trapped!
Sample Input
3 4 5 S.... .###. .##.. ###.# ##### ##### ##.## ##... ##### ##### #.### ####E 1 3 3 S## #E# ### 0 0 0
Sample Output
Escaped in 11 minute(s). Trapped!
题目大意:
给出一三维空间的地牢,要求求出由字符'S'到字符'E'的最短路径
移动方向可以是上,下,左,右,前,后,六个方向
每移动一次就耗费一分钟,要求输出最快的走出时间。
不同L层的地图,相同RC坐标处是连通的。
其中'S'是入口,'E'是出口,'#'是墙壁,'.'是通路。
解析:求最短路问题,直接BFS
另外附上一组样例:
input:
3 4 5 S.... .###. .##.. ###.# ##### ##### ##.## ##... ##### ##### #.### ####E 1 3 3 S## #E# ### 4 4 5 ##### ##### ##.## ##... ##### ###S# #.#.# #.... ##### ##### #.### ####E ##### #...# ...## #.... 1 2 2 ## SE 3 3 3 ### #E# #.# #.. .## .#. ... ... ..S 5 2 2 ## ## #. .. .S .. .. .. .E .. 2 1 1 S E 1 1 2 SE 1 5 5 ##### S#### ....# ####E ##... 2 3 3 #.E ... ... ... ... ..S 2 4 4 #### #S## .... ###. #### .### .### .E.. 2 5 5 ##### #S..# ..#.. .###. .###. ##### ##### ##### ##### ..E.. 0 0 0
output:
Escaped in 11 minute(s). Trapped! Escaped in 4 minute(s). Escaped in 1 minute(s). Trapped! Escaped in 2 minute(s). Escaped in 1 minute(s). Escaped in 1 minute(s). Trapped! Escaped in 3 minute(s). Escaped in 5 minute(s). Escaped in 7 minute(s).
#include <iostream> #include <queue> #include <stdio.h> #include <string.h> using namespace std; const int N = 31; const int dx[6]={1,-1,0,0,0,0}; const int dy[6]={0,0,1,-1,0,0}; const int dz[6]={0,0,0,0,1,-1}; char grid[N][N][N]; struct Node{ int x,y,z,step; }; int l,r,c; Node start,end; int bfs(Node s) { grid[s.x][s.y][s.z] = '#'; if(s.x==end.x && s.x==end.y && s.z==end.z) { return s.step; } queue<Node> Q; Q.push(s); Node tmp; while(!Q.empty()) { Node now; now = Q.front(); Q.pop(); for(int i = 0; i < 6; i++) { tmp.x = now.x + dx[i]; tmp.y = now.y + dy[i]; tmp.z = now.z + dz[i]; tmp.step = now.step + 1; if(tmp.x==end.x && tmp.y==end.y && tmp.z==end.z) { return tmp.step; } if(tmp.x>=0 && tmp.x<l && tmp.y>=0 && tmp.y<r && tmp.z>=0 && tmp.z<c && grid[tmp.x][tmp.y][tmp.z]=='.') { grid[tmp.x][tmp.y][tmp.z]='#'; Q.push(tmp); } } } return -1; } int main() { while(~scanf("%d%d%d",&l,&r,&c) && (l || r || c)) { for(int i=0;i<l;i++) { for(int j=0;j<r;j++) { scanf("%s",grid[i][j]); for(int k=0;k<c;k++) { if( grid[i][j][k]=='S') { start.x=i; start.y=j; start.z=k; start.step = 0; } if( grid[i][j][k]=='E') { end.x=i; end.y=j; end.z=k; } } } } int ans; ans = bfs(start); if(ans!=-1) printf("Escaped in %d minute(s).\n",ans); else printf("Trapped!\n"); memset(grid,0,sizeof(grid)); } return 0; }