题目描述
bfs
(一)WE
if(nx<1||nx>r||ny<1||ny>c||nz<1||nz>l||g[nx][ny][nz]=='#'||st[nx][ny][nz]){continue;}
(二)
bool check(int nx, int ny, int nz)
{
return nx<1||nx>r||ny<1||ny>c||nz<1||nz>l;
}
if(check(nx,ny,nz)||g[nx][ny][nz]=='#'||st[nx][ny][nz]){continue;}
算法1
C++ 代码
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int INF=0x3f3f3f;
const int N=110;
int l,r,c;
char g[N][N][N];
int dist[N][N][N];
bool st[N][N][N];
struct position{
int x,y,z;
};
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};
bool check(int nx, int ny, int nz) //判断是否在地图内
{
return nx<1||nx>r||ny<1||ny>c||nz<1||nz>l;
}
void bfs(position start,position end){
memset(dist,-1,sizeof(dist));
memset(st,false,sizeof(st));
queue<position> q;
dist[start.x][start.y][start.z]=0;
st[start.x][start.y][start.z]=true;
q.push(start);
while(q.size()){
position t=q.front();q.pop();
int a=t.x,b=t.y,c=t.z;
for(int i=0;i<6;i++){
int nx=a+dx[i],ny=b+dy[i],nz=c+dz[i];
// if(nx<1||nx>r||ny<1||ny>c||nz<1||nz>l||g[nx][ny][nz]=='#'||st[nx][ny][nz]){continue;}
//为什么上面的不可以,但是下面的可以??
if(check(nx,ny,nz)||g[nx][ny][nz]=='#'||st[nx][ny][nz]){continue;}
if(dist[nx][ny][nz]==-1){
dist[nx][ny][nz]=dist[a][b][c]+1;
st[nx][ny][nz]=true;
q.push({nx,ny,nz});
}
}
}
}
int main(){
while(cin>>l>>r>>c){
if(l==0&&r==0&&c==0){
break;
}
position start,end;
for(int k=1;k<=l;k++){
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
cin>>g[i][j][k];
if(g[i][j][k]=='S'){
start={i,j,k};
}
if(g[i][j][k]=='E'){
end={i,j,k};
}
}
}
}
bfs(start,end);
if(dist[end.x][end.y][end.z]==-1){
cout<<"Trapped!"<<endl;
}else{
cout<<"Escaped in "<<dist[end.x][end.y][end.z]<<" minute(s)."<<endl;
}
}
return 0;
}