poj2251 Dungeon Master bfs
题目链接:http://poj.org/problem?id=2251
题目大意:
给出一三维空间的地牢,要求求出由字符'S'到字符'E'的最短路径
移动方向可以是上,下,左,右,前,后,六个方向
每移动一次就耗费一分钟,要求输出最快的走出时间。
不同L层的地图,相同RC坐标处是连通的
简单的bfs
1 ///2014.3.30 - 2014.4.2 2 ///poj2251 3 4 #include <iostream> 5 #include <cstdio> 6 using namespace std; 7 8 int L,R,C; 9 char maze[40][40][40]; 10 bool visted[40][40][40]; 11 struct position 12 { 13 char l,r,c; ///由于l,r,c均小于40,这里把char当作单字节整数用 14 int step; 15 }; 16 position s,e; 17 18 int addR[6] = {-1,0,1,0,0,0}; 19 int addC[6] = {0,-1,0,1,0,0}; 20 int addL[6] = {0,0,0,0,1,-1}; 21 22 void init(){ 23 char temp; 24 for(int i=1 ; i<=L ; i++){ 25 for(int j=1 ; j<=R ; j++){ 26 for(int k=1 ; k<=C ; k++){ 27 cin>>temp; 28 if( temp == 'S' ){ 29 s.l=i , s.r=j , s.c=k ,s.step=0 ; 30 } 31 if( temp == 'E' ){ 32 temp = '.'; 33 e.l=i , e.r=j , e.c=k ,e.step=-1; 34 } 35 maze[i][j][k] = temp; 36 visted[i][j][k] = false; 37 } 38 } 39 } 40 } 41 42 int bfs(position pos){ 43 position queue[30000]; 44 int head,tail; 45 queue[0] = pos; 46 queue[0].step = 0; 47 visted[pos.l][pos.r][pos.c] = true; 48 head = 0; 49 tail = 1; 50 51 bool find = false; 52 while( head<tail && !find ){ 53 for(int i=0 ; i<6 ; i++){ 54 if( queue[head].l+addL[i]>=1 && queue[head].l+addL[i]<=L && 55 queue[head].r+addR[i]>=1 && queue[head].r+addR[i]<=R && 56 queue[head].c+addC[i]>=1 && queue[head].c+addC[i]<=C && 57 !visted[ queue[head].l+addL[i] ][ queue[head].r+addR[i] ][ queue[head].c+addC[i] ] && 58 maze[ queue[head].l+addL[i] ][ queue[head].r+addR[i] ][ queue[head].c+addC[i] ]=='.' ){ 59 queue[tail].l = queue[head].l + addL[i]; 60 queue[tail].r = queue[head].r + addR[i]; 61 queue[tail].c = queue[head].c + addC[i]; 62 queue[tail].step = queue[head].step + 1; 63 visted[ queue[tail].l ][ queue[tail].r ][ queue[tail].c ] = true; 64 if( queue[tail].l==e.l && queue[tail].r==e.r && queue[tail].c==e.c ){ 65 find = true; 66 break; 67 } 68 tail++; 69 } 70 } 71 head++; 72 } 73 74 if( find ){ 75 return queue[tail].step; 76 } 77 else 78 return -1; 79 } 80 81 int main() 82 { 83 // freopen("in","r",stdin); 84 // freopen("out","w",stdout); 85 86 while( cin>>L>>R>>C && L && R && C ){ 87 init(); 88 89 int time = bfs(s); 90 if( time==-1 ) 91 cout<<"Trapped!"<<endl; 92 else 93 cout<<"Escaped in "<<time<<" minute(s)."<<endl; 94 } 95 return 0; 96 }