题意:L层,R行,C列,S起点,E终点,‘#’障碍,可以走上下前后左右6个方向,走一步一秒,问至少需要几秒,可能无解
简单BFS
代码如下:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int l, r, c;
int s1, s2, s3, e1, e2, e3;
int vis[35][35][35];
char map[35][35][35];
int f[6][3] = {{0,-1,0}, {0,0,1}, {0,1,0}, {0,0,-1}, {1,0,0}, {-1,0,0}};
struct node
{
int x, y, z, st;
};
int check(node b)
{
if(vis[b.x][b.y][b.z]) return 1;
else if(b.x >= l || b.y >= r || b.z >= c || b.x <0 || b.y < 0 || b.z < 0) return 1;
else if(map[b.x][b.y][b.z] == '#') return 1;
return 0;
}
int bfs()
{
memset(vis, 0, sizeof(vis));
node s, nex;
s.x = s1, s.y = s2, s.z = s3, s.st = 0;
queue<node>q;
q.push(s);
while(!q.empty())
{
node a = q.front();
q.pop();
if(a.x == e1 && a.y == e2 && a.z == e3) return a.st;
for(int i = 0; i < 6; i++)
{
nex = a;
nex.x += f[i][0];
nex.y += f[i][1];
nex.z += f[i][2];
if(check(nex)) continue;
vis[nex.x][nex.y][nex.z] = 1;
++nex.st;
q.push(nex);
}
}
return 0;
}
int main()
{
while(cin>> l >> r >> c)
{
if(l == 0 && r == 0 && c == 0) break;
for(int k = 0; k < l; k++)
{
for(int i = 0; i < r; i++)
{
getchar();
for(int j = 0; j < c; j++)
{
scanf("%c", &map[k][i][j]);
if(map[k][i][j] == 'S') s1 = k, s2 = i, s3 = j;
else if(map[k][i][j] == 'E') e1 = k, e2 = i, e3 = j;
}
}
getchar();
}
int ans = bfs();
if(ans) printf("Escaped in %d minute(s).\n", ans);
else printf("Trapped!\n");
}
return 0;
}