问题描述:
给你一个三维地牢,‘.’代表可以走的点,‘#’代表不可走的点,‘S’代表开始点,‘E’代表结束点。问从‘S’开始能不能走出地牢,能的话要用多长时间,不能输出不能,输入输出见原题目。
题目链接:POJ NO.2251
思路:
多了一个方向,其他和普通bfs一样。
代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
#include<vector>
#include<set>
#define INF 0x3f3f3f3f
#define PI 3.1415926
#define MAX 40
using namespace std;
struct node{
char x, y, z;
int t;
};
char mp[MAX][MAX][MAX];
int l, m, c, bx, by, bz;
int xx[]={1,-1,0,0,0,0};
int yy[]={0,0,0,0,-1,1};
int zz[]={0,0,-1,1,0,0};
bool visit[MAX][MAX][MAX];
int bfs(){
memset(visit, false, sizeof(visit));
queue<node> que;
que.push((node){
bx, by, bz,0
});
while(!que.empty()){
node p = que.front();
que.pop();
if(mp[p.x][p.y][p.z] == 'E') return p.t;
if(visit[p.x][p.y][p.z]) continue;
visit[p.x][p.y][p.z] = true;
for(int i = 0; i < 6; i++){
node n;
n.x = p.x + xx[i];
n.y = p.y + yy[i];
n.z = p.z + zz[i];
n.t = p.t + 1;
if(0 <= n.x && n.x < l && 0 <= n.y && n.y < m &&
0 <= n.z && n.z < c && !visit[n.x][n.y][n.z] &&
mp[n.x][n.y][n.z] != '#'){
que.push(n);
}
}
}
return -1;
}
int main(){
while(~scanf("%d%d%d", &l, &m, &c)){
if(l + m + c == 0){
break;
}
for(int i = 0; i < l; i++){
for(int j = 0; j < m; j++){
scanf("%s", &mp[i][j]);
for(int k = 0; k < c; k++){
if(mp[i][j][k] == 'S'){
bx = i, by = j, bz = k;
}
}
}
}
int res = bfs();
if(res == -1){
printf("Trapped!\n");
}else
printf("Escaped in %d minute(s).\n", res);
}
return 0;
}