dfs,从四个方向到六个方向。
找到起点和终点,
刚开始dfs里最后一行的return 0没写,导致一直出错
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
int l,r,c,count1;
int sx,sy,sz,ex,ey,ez;
char dungeon[31][31][31];
int direct[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}}; //注意给二维数组赋值的格式,总会忘
int hasadd[31][31][31];
struct node{ //x,y,z坐标,及到该点已经走了几步
int x;
int y;
int z;
int hasstep;
};
int canwalk(node a){ //判断该点可不可以走
if(a.x<0||a.y<0||a.z<0||a.x>=l||a.y>=r||a.z>=c){ //出界
return 0;
}
else if(dungeon[a.x][a.y][a.z]=='#'){ //石头
return 0;
}
else if(hasadd[a.x][a.y][a.z]==1){ //已经走过这个点了
return 0;
}
return 1;
}
int dfs(){
queue<node> Q;
node start,temp,next;
start.x=sx;
start.y=sy;
start.z=sz;
start.hasstep=0;
hasadd[sx][sy][sz]=1;
Q.push(start);
while(!Q.empty()){
temp=Q.front();
Q.pop();
if(temp.x==ex&&temp.y==ey&&temp.z==ez){ //找到了终点
return temp.hasstep;
}
for(int i=0;i<6;i++){ //把temp节点的六个方向都检查一下看看能不能走
next.x=temp.x+direct[i][0];
next.y=temp.y+direct[i][1];
next.z=temp.z+direct[i][2];
if(canwalk(next)){ //如果next可以走
hasadd[next.x][next.y][next.z]=1;
next.hasstep=temp.hasstep+1;
Q.push(next);
}
else;
}
}
return 0;
}
int main(){
while(cin>>l>>r>>c){
if(l==0&&r==0&&c==0){
break;
}
for(int i=0;i<l;i++){
for(int j=0;j<r;j++){
cin>>dungeon[i][j];
for(int k=0;k<c;k++){ //顺便找起点和终点
if(dungeon[i][j][k]=='S'){
sx=i;
sy=j;
sz=k;
}
else if(dungeon[i][j][k]=='E'){
ex=i;
ey=j;
ez=k;
}
}
}
}
memset(hasadd,0,sizeof(hasadd));
count1=0; //结果
count1=dfs();
if(count1>0){
cout<<"Escaped in "<<count1<<" minute(s)."<<endl;
}
else{
cout<<"Trapped!"<<endl;
}
}
return 0;
}