POJ 2251 Dungeon Master
题目见此:http://poj.grids.cn/practice/2251/
解题思路:
- 一道BFS简单题,可以用来练手
- 唯一值得说一下的就是31,32行处不要写成x=i, y=j, z=k,因为i、z表示层数,j、x表示行数,k、y表示列数
贴代码:
1 #include <iostream> 2 #include <queue> 3 #include <string.h> 4 using namespace std; 5 6 bool b[32][32][32]; 7 int r, c, l; 8 int dx[6]={0, 0, 1, 0, 0, -1}, dy[6]={0, 1, 0, 0, -1, 0}, dz[6]={1, 0, 0, -1, 0, 0}; 9 10 struct Node 11 { 12 int x, y, z, time; 13 bool operator == (const Node& a) const 14 { 15 if(x == a.x && y == a.y && z == a.z) return 1; 16 else return 0; 17 } 18 }p, q; 19 20 int main() 21 { 22 while(cin >> l >> r >> c, r || c || l) 23 { 24 memset(b, 0, sizeof(b)); 25 for(int i=1 ; i<=l ; i++) 26 for(int j=1 ; j<=r ; j++) 27 for(int k=1 ; k<=c ; k++) 28 { 29 char ch; 30 cin >> ch; 31 if(ch == 'S') {p.z = i, p.x = j, p.y = k, p.time = 0;} 32 else if(ch == 'E') {q.z = i, q.x = j, q.y = k; b[i][j][k] = 1;} 33 else if(ch == '.') b[i][j][k] = 1; 34 } 35 queue<Node> Q; 36 Q.push(p); 37 bool f = 0; 38 while(!Q.empty()) 39 { 40 p = Q.front() ; Q.pop(); 41 if(p == q) 42 { 43 f = 1; 44 break; 45 } 46 Node now; 47 now.time = p.time + 1; 48 for(int k=0 ; k<6 ; k++) 49 { 50 now.x = p.x + dx[k], now.y = p.y + dy[k], now.z = p.z + dz[k]; 51 if(b[now.z][now.x][now.y]) 52 { 53 Q.push(now); 54 b[now.z][now.x][now.y] = 0; 55 } 56 } 57 } 58 if(f == 1) 59 cout << "Escaped in " << p.time << " minute(s)." << endl; 60 else 61 cout << "Trapped!" << endl; 62 } 63 }