題目大意:有一個三維迷宮,起始點爲S,終點爲E,需要判斷從S點能不能走到E點,如果可以輸出最短時間,如果不行,輸出Trapped!
思路:從S點開始bfs 與一般bfs不同的是有六個方向可以走,bfs道E點輸出時間,不行輸出Trapped!即可剛開始學搜索,第一次用dfs直接tle dfs就AC了
#include<stdio.h>
#include<string.h>
int x,y,z;
int x_s,y_s,z_s,x_e,y_e,z_e;
char map[40][40][40];//存迷宮
int book[40][40][40];//標記是否走過
int s[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,-1},{0,0,1}};//六個方向
struct node{
int x;
int y;
int z;
int step;
}queue[30000];//開隊列 用來bfs存步數
int check(int x_c,int y_c,int z_c){//判斷這個點是否可以走
if(x_c>=0&&x_c<x&&y_c>=0&&y_c<y&&z_c>=0&&z_c<z&&book[x_c][y_c][z_c]==0&&map[x_c][y_c][z_c]!='#')
return 1;
return 0;
}
void bfs();
int main(void)
{
while(scanf("%d%d%d",&x,&y,&z),x&&y&&z){
int i,j,k;
for(i=0;i<x;i++){
getchar();
for(j=0;j<y;j++){
memset(book[i][j],0,31);
for(k=0;k<z;k++){
scanf("%c",&map[i][j][k]);
if(map[i][j][k]=='S'){
x_s=i;y_s=j;z_s=k;//起點
}
if(map[i][j][k]=='E'){
x_e=i;y_e=j;z_e=k;//終點
}
}
getchar();
}
}
memset(book,0,sizeof(book));
bfs( );
}
return 0;
}
void bfs(){
struct node temp;
book[x_s][y_s][z_s]=1;
int head=0;
int tail=1;
queue[head].x=temp.x=x_s;
queue[head].y=temp.y=y_s;
queue[head].z=temp.z=z_s;
queue[head].step=0;
while(head<tail){
int i;
if(queue[head].x==x_e&&queue[head].y==y_e&&queue[head].z==z_e){//判斷是否到達終點
printf("Escaped in %d minute(s).\n",queue[head].step);
return ;
}
for(i=0;i<6;i++){//走六個方向
temp.x=queue[head].x+s[i][0];
temp.y=queue[head].y+s[i][1];
temp.z=queue[head].z+s[i][2];
if(check(temp.x,temp.y,temp.z)){
book[temp.x][temp.y][temp.z]=1;
queue[tail].x=temp.x;
queue[tail].y=temp.y;
queue[tail].z=temp.z;
queue[tail].step=queue[head].step+1;
tail++;
}
} head++;
}
printf("Trapped!\n");//如果用bfs沒找到,輸出trapped!
}