题目地址
AC代码
#include <iostream>
#include <algorithm>
#include <utility>
#include <cstring>
#include <queue>
using namespace std;
class point{
public:
int x;
int y;
int z;
point(int ix,int iy,int iz):x(ix),y(iy),z(iz){}
point(){}
void operator=(point ¶){
this->x=para.x;
this->y=para.y;
this->z=para.z;
}
};
int ditu[35][35][35];
int mark[35][35][35];
int main() {
ios::sync_with_stdio(false);
int z,y,x,SZ,SY,SX;
while(cin>>z>>y>>x,x!=0&&y!=0&&z!=0){
memset(mark,0, sizeof(mark));
for (int i = 1; i <= z; ++i) {
for (int j = 1; j <= y; ++j) {
for (int k = 1; k <= x; ++k) {
char temp;
cin>>temp;
if(temp=='S'){
SZ = i,SY = j,SX = k;
ditu[i][j][k]=1;
}else if(temp == '.'){
ditu[i][j][k]=1;
}else if(temp == '#'){
ditu[i][j][k]=0;
}else if(temp == 'E'){
ditu[i][j][k]=2;
}
}
}
}
queue<pair<point,int> >list;
point temp(SX,SY,SZ);
list.push(make_pair(temp,0));
mark[SZ][SY][SX]=1;
int boo = 0,ans = 0;
while(!list.empty()){
temp = list.front().first;
int dis = list.front().second;
list.pop();
if(ditu[temp.z][temp.y][temp.x]==2){
boo = 1;
ans= dis;
break;
}else if(ditu[temp.z][temp.y][temp.x]==1){
if(temp.z+1<=z&&ditu[temp.z+1][temp.y][temp.x]!=0&&mark[temp.z+1][temp.y][temp.x]==0){
point next = temp;
next.z+=1;
list.push(make_pair(next,dis+1));
mark[temp.z+1][temp.y][temp.x]=1;
}
if(temp.z-1>=0&&ditu[temp.z-1][temp.y][temp.x]!=0&&mark[temp.z-1][temp.y][temp.x]==0){
point next = temp;
next.z-=1;
list.push(make_pair(next,dis+1));
mark[temp.z-1][temp.y][temp.x]=1;
}
if(temp.y+1<=y&&ditu[temp.z][temp.y+1][temp.x]!=0&&mark[temp.z][temp.y+1][temp.x]==0){
point next = temp;
next.y+=1;
list.push(make_pair(next,dis+1));
mark[temp.z][temp.y+1][temp.x]=1;
}
if(temp.y-1>=0&&ditu[temp.z][temp.y-1][temp.x]!=0&&mark[temp.z][temp.y-1][temp.x]==0){
point next = temp;
next.y-=1;
list.push(make_pair(next,dis+1));
mark[temp.z][temp.y-1][temp.x]=1;
}
if(temp.x+1<=x&&ditu[temp.z][temp.y][temp.x+1]!=0&&mark[temp.z][temp.y][temp.x+1]==0){
point next = temp;
next.x+=1;
list.push(make_pair(next,dis+1));
mark[temp.z][temp.y][temp.x+1]=1;
}
if(temp.x-1>=0&&ditu[temp.z][temp.y][temp.x-1]!=0&&mark[temp.z][temp.y][temp.x-1]==0){
point next = temp;
next.x-=1;
list.push(make_pair(next,dis+1));
mark[temp.z][temp.y][temp.x-1]=1;
}
}
}
if(boo)cout<<"Escaped in "<<ans<<" minute(s)."<<endl;
else cout<<"Trapped!"<<endl;
}
return 0;
}
题解和题目思路
还是一道BFS的题目,只不过从平面BFS变成了立体BFS,照着写就是,但是要注意剪枝的问题,如果剪的不好或者干脆直接没剪的话会导致严重的MLE和TLE(看了看菜鸡的自己)下次注意点就行