UVA532-Dungeon Master(三维迷宫)
还是广搜的题,只不过题意有点吓人,什么三维的迷宫,搜索最短的路径。
题目不难。不作多余的解释;
代码如下:
#include <iostream> #include <cstring> using namespace std; struct Node{ int x,y,z,len; }; char ch[40][40][40]; bool vis[40][40][40]; int go[6][3] = {{-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,1},{0,0,-1}};//需要遍历的六个方向 int l, r, c, x_, y_ , z_; Node node[30000];//用于存储节点的队列 int pan(int x,int y, int z) { if(x>=0&&x<l&&y>=0&&y<r&&z>=0&&z<c&&!vis[x][y][z]&&ch[x][y][z]=='.')return 1; return 0; } void input() { for(int i = 0; i < l; i++,cin.ignore()) for(int j = 0; j < r; j++,cin.ignore()) for(int k = 0; k < c; k++) { ch[i][j][k] = cin.get(); if(ch[i][j][k] == 'S'){x_ = i; y_ = j; z_ = k;}//输入的时候就把起点找出来 } } int bfs() { int rear = 0, front = 0; node[0].x = x_; node[0].y = y_; node[0].z = z_; node[0].len = 0; while(front>=rear) { int _x = node[rear].x, _y = node[rear].y, _z = node[rear].z, _len = node[rear].len; int fx, fy, fz, flen; for(int i = 0; i < 6; i++) { fx = _x+go[i][0]; fy = _y+go[i][1]; fz = _z+go[i][2], flen = _len+1; if(ch[fx][fy][fz] == 'E'){return flen;} if(pan(fx, fy, fz)){++front;node[front].x = fx;node[front].y = fy; node[front].z = fz; node[front].len = flen;} vis[fx][fy][fz] = 1; } rear++; } return 0; } int main () { int len; while(cin>>l>>r>>c&&l&&r&&c) { cin.get(); //需要特别注意之处,还要把回车读取了。 memset(ch,0,sizeof(ch)); memset(vis,0,sizeof(vis)); len = 0; input();//cout<<"end"; len = bfs(); if(len)cout<<"Escaped in "<<len<<" minute(s)."<<endl; else cout<<"Trapped!"<<endl; } return 0; }