uva532--3d迷宫--bfs

193 阅读1分钟

题意:三维的bfs,给定迷宫的入口和出口,让你求出来的最短时间,其实就是求最短路径。

思路:我一定要说出题目的坑点,不然我白调试了一下午。首先起点不一定是在左上角,也不一定是在最底层,还有就是每层之间的输入都有空行。搜索的时候就是六个方向的搜索,上下前后左右,找到之后就可以计算步数了。

#include <iostream>
#include<cstring>
using namespace std; 
char maze[35][35][35];
int  L,R,C,count,flag=0;
int east[]={0,0,1,-1,0,0};
int north[]={-1,1,0,0,0,0};
int up[]={0,0,0,0,1,-1};
struct {
	int x,y,z,pre;
}buff[1000000];
void print(int p){
	if(buff[p].pre!=-1){
		print(buff[p].pre);
		count++;
	}
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void bfs(int s1,int s2,int s3){
	buff[0].pre=-1;
	buff[0].x=s1;buff[0].y=s2;buff[0].z=s3;
	int now=0,bu=0,nx,ny,nz,fo=1;
	while(bu<fo){
		now=bu;
		for(int i=0;i<6;i++){
			nx=buff[now].x+east[i];
			ny=buff[now].y+north[i];
			nz=buff[now].z+up[i];
			if(nx<0||ny<0||nz<0||nx>=C||ny>=R||nz>=L||maze[nz][ny][nx]=='#'||maze[nz][ny][nx]=='S')
				continue;
		else{
			if(maze[nz][ny][nx]=='E'){
			flag=1;
			print(bu);
			 return;
			}
			maze[nz][ny][nx]='#';
			buff[fo].pre=bu;
			buff[fo].x=nx;buff[fo].y=ny;
			buff[fo].z=nz;
			fo++;		
		}
		}
		bu++;
	}	
}
int main(int argc, char** argv) {
	while(scanf("%d %d %d",&L,&R,&C)&&L&&R&&C){
		count=1;flag=0;
		int sz,sy,sx; 
		//memset(buff,0,sizeof(buff));
		for(int i=0;i<L;i++){
			for(int j=0;j<R;j++){
				for(int k=0;k<C;k++){
					cin>>maze[i][j][k];
					if(maze[i][j][k]== 'S') {
						sz=i;sy=j;sx=k;
					}
				}
			}
		}
		maze[0][0][0]='S';
		getchar();
		getchar();
		bfs(sx,sy,sz);
		if(flag)
		printf("Escaped in %d minute(s).\n",count);
		else 
		printf("Trapped!\n");			
	}	
	return 0;
}


\

\

\