POJ 2251 Dungeon Master
三维简单BFS
You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides.
Is an escape possible? If yes, how long will it take?
L is the number of levels making up the dungeon.
R and C are the number of rows and columns making up the plan of each level.
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a '#' and empty cells are represented by a '.'. Your starting position is indicated by 'S' and the exit by the letter 'E'. There's a single blank line after each level. Input is terminated by three zeroes for L, R and C. Output Each maze generates one line of output. If it is possible to reach the exit, print a line of the form Escaped in x minute(s). where x is replaced by the shortest time it takes to escape.
If it is not possible to escape, print the line Trapped! Sample Input 3 4 5
S....
.###.
.##..
###.#
#####
#####
##.##
##...
#####
#####
#.###
####E
1 3 3
S##
#E#
###
0 0 0
Sample Output Escaped in 11 minute(s).
Trapped!
很简单很简单的BFS,但是迷之WA了…暂时找不出错误,记录一下这道题,过几天再看看哪里错了。
错误的代码↓
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
int L,R,C;
typedef struct{
int x,y,z;
}node;
node S,E;
node IN,OUT;
queue<node> Q;
char dun[35][35][35];
bool vis[35][35][35];
int dis[35][35][35];
int dx[6]={1,-1,0,0,0,0},
dy[6]={0,0,1,-1,0,0},
dz[6]={0,0,0,0,1,-1};
int bfs(){
int i,j,k;
while(!Q.empty()){
OUT=Q.front();
Q.pop();
for(i=0;i<6;i++){
IN.x=OUT.x+dx[i];
IN.y=OUT.y+dy[i];
IN.z=OUT.z+dz[i];
if(IN.x>=L||IN.x<0||IN.y>=R||IN.y<0||IN.z>=C||IN.z<0)
continue;
if(vis[IN.x][IN.y][IN.z]==1)
continue;
dis[IN.x][IN.y][IN.z]=dis[OUT.x][OUT.y][OUT.z]+1;
if(dun[IN.x][IN.y][IN.z]=='E'){
return 0;
}
vis[IN.x][IN.y][IN.z]=1;
Q.push(IN);
}
}
return 0;
}
int main(){
int i,j,k;
char store;
while(scanf("%d %d %d",&L,&R,&C)!=EOF){
if(L==0&&R==0&&C==0)
break;
for(i=0;i<L;i++){
for(j=0;j<R;j++){
scanf("%s",dun[i][j]);
}
scanf("%c",&store);
}
while(!Q.empty())
Q.pop();
memset(dis,-1,sizeof(dis));
for(i=0;i<L;i++){
for(j=0;j<R;j++){
for(k=0;k<C;k++){
if(dun[i][j][k]=='S'){
S.x=i;
S.y=j;
S.z=k;
}
if(dun[i][j][k]=='E'){
E.x=i;
E.y=j;
E.z=k;
}
if(dun[i][j][k]=='#')
vis[i][j][k]=1;
if(dun[i][j][k]=='.')
vis[i][j][k]=0;
}
}
}
dis[S.x][S.y][S.z]=0;
vis[S.x][S.y][S.z]=1;
Q.push(S);
bfs();
if(dis[E.x][E.y][E.z]==-1)
printf("Trapped!\n");
else
printf("Escaped in %d minute(s).\n",dis[E.x][E.y][E.z]);
}
return 0;
}