Is an escape possible? If yes, how long will it take?
Input
L is the number of levels making up the dungeon.
R and C are the number of rows and columns making up the plan of each level.
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a '#' and empty cells are represented by a '.'. Your starting position is indicated by 'S' and the exit by the letter 'E'. There's a single blank line after each level. Input is terminated by three zeroes for L, R and C.
Escaped in x minute(s).
where x is replaced by the shortest time it takes to escape.
If it is not possible to escape, print the line
Trapped!
3 4 5 S.... .###. .##.. ###.# ##### ##### ##.## ##... ##### ##### #.### ####E 1 3 3 S## #E# ### 0 0 0Sample Output
Escaped in 11 minute(s). Trapped!
3維迷宮問題。每次可以向上,向下,向左,向右,向前,向後走。從起始點走到終點,求最小步數。我們可以用bfs,每次將六種情況壓入隊列(只要此位置能走而且沒有走過)。沒有什麼很特殊的情況,直接暴力搜索就行。數組我們可以多開一點,把邊界以外的都設爲岩石(不能走),這樣因爲走不出去我們就可以不用判斷邊界的情況了。
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int a[34][34][34]; //用來表示迷宮。其中-1表示岩石,0表示可以走(輸入字符的時候裝換一下就行了)
bool b[34][34][34]; //用來判斷是否走過此位置
int n,m,S;
struct f {
int x,y,z,s; //s表示步數
};
f start,end; //起點和終點
void bfs() {
queue<f> q;
q.push(start);
f p,c;
memset(b,0,sizeof(b));
while(!q.empty()) {
p=q.front() ;
q.pop();
if(p.x==end.x&&p.y==end.y&&p.z==end.z) { //到達終點,更新終點的步數
end.s=p.s;
return ;
}
if(a[p.x+1][p.y][p.z]==0&&b[p.x+1][p.y][p.z]==0) {
c.x=p.x+1;
c.y=p.y;
c.z=p.z;
c.s=p.s+1;
q.push(c);
b[p.x+1][p.y][p.z]=1;
}
if(a[p.x-1][p.y][p.z]==0&&b[p.x-1][p.y][p.z]==0) {
c.x=p.x-1;
c.y=p.y;
c.z=p.z;
c.s=p.s+1;
q.push(c);
b[p.x-1][p.y][p.z]=1;
}
if(a[p.x][p.y+1][p.z]==0&&b[p.x][p.y+1][p.z]==0) {
c.x=p.x;
c.y=p.y+1;
c.z=p.z;
c.s=p.s+1;
q.push(c);
b[p.x][p.y+1][p.z]=1;
}
if(a[p.x][p.y-1][p.z]==0&&b[p.x][p.y-1][p.z]==0) {
c.x=p.x;
c.y=p.y-1;
c.z=p.z;
c.s=p.s+1;
q.push(c);
b[p.x][p.y-1][p.z]=1;
}
if(a[p.x][p.y][p.z+1]==0&&b[p.x][p.y][p.z+1]==0) {
c.x=p.x;
c.y=p.y;
c.z=p.z+1;
c.s=p.s+1;
q.push(c);
b[p.x][p.y][p.z+1]=1;
}
if(a[p.x][p.y][p.z-1]==0&&b[p.x][p.y][p.z-1]==0) {
c.x=p.x;
c.y=p.y;
c.z=p.z-1;
c.s=p.s+1;
q.push(c);
b[p.x][p.y][p.z-1]=1;
}
}
}
int main() {
int L,R,C;
while(cin>>L>>R>>C) {
if(L==0&&R==0&&C==0)
break;
char t;
memset(a,-1,sizeof(a)); //先全部設爲岩石,輸入.時我們在變爲可以走
for(int i=1; i<=L; i++) { //從1開始,邊界0爲岩石,這樣我們就不用判斷邊界了
for(int j=1; j<=R; j++) {
for(int k=1; k<=C; k++) {
cin>>t;
if(t=='S') {
start.x=i;
start.y=j;
start.z=k;
start.s=0;
} else if(t=='.')
a[i][j][k]=0;
else if(t=='E') {
end.x=i;
end.y=j;
end.z=k;
a[i][j][k]=0;
}
}
}
}
end.s=0;
bfs();
if(end.s!=0)
cout<<"Escaped in "<<end.s<<" minute(s)."<<endl;
else
cout<<"Trapped!"<<endl;
}
return 0;
}