题目:Dungeon Master
题目大意:
- 从起点(‘S’)坐标到终点(‘E’)坐标的最短距离,有6个方向:上,下,东,西,南,北
- 数据偏小,三维BFS求最短距离
代码如下:
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define inf 0x3f3f3f3f
#define mm(a,x) memset(a,x,sizeof a)
const int N = 40;
struct Node {
int z,x,y;
Node(int a,int b,int c){
z = a,x = b,y = c;
}
};
int l,n,m;
char g[N][N][N];
int dist[N][N][N];
int dx[6] = {0,0,0,1,0,-1};
int dy[6] = {0,0,1,0,-1,0};
int dz[6] = {1,-1,0,0, 0,0};
int xa,ya,za,xb,yb,zb;
int bfs(int x,int y,int z) {
queue<Node> q;
mm(dist,inf);
dist[z][x][y] = 0;
q.push(Node(z,x,y));
while(q.size()) {
Node t = q.front();
q.pop();
for(int i = 0; i < 6; i ++ ) {
int c = t.z + dz[i];
int a = t.x + dx[i];
int b = t.y + dy[i];
if(c < 1 || c > l || a < 1 || a > n || b < 1 || b > m) continue;
if(dist[c][a][b] != inf || g[c][a][b] == '#') continue;
q.push(Node(c,a,b));
dist[c][a][b] = dist[t.z][t.x][t.y] + 1;
}
}
return dist[zb][xb][yb];
}
int main() {
while(cin >> l >> n >> m,l,n,m) {
for(int i = 1; i <= l; i ++) {
for(int j = 1; j <= n; j ++ ) {
for(int k = 1; k <= m; k ++ ) {
cin >> g[i][j][k];
if(g[i][j][k] == 'S') {
za = i,xa = j, ya = k;
}
if(g[i][j][k] == 'E') {
zb = i,xb = j, yb = k;
}
}
}
}
int t = bfs(xa,ya,za);
if(t == inf) {
cout<<"Trapped!"<<endl;
} else {
printf("Escaped in %d minute(s).\n",t);
}
}
return 0;
}