三维矩阵的bfs
C++ 代码
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int N = 110;
char g[N][N][N];
int d[N][N][N];
int l, r, c;
struct Point{
int x, y, z;
}st, ed;
int dx[6] = {1, -1, 0, 0, 0, 0};
int dy[6] = {0, 0, 1, -1, 0, 0};
int dz[6] = {0, 0, 0, 0, 1, -1};
int bfs()
{
memset(d, -1, sizeof d);
queue<Point> q;
q.push(st);
d[st.z][st.x][st.y] = 0;
while(!q.empty())
{
auto p = q.front();
q.pop();
for(int i = 0; i < 6; ++ i){
int x = p.x + dx[i], y = p.y + dy[i], z = p.z + dz[i];
if(x < 0 || x >= r || y < 0 || y >= c || z < 0 || z >= l) continue;
if(g[z][x][y] == '#' || d[z][x][y] != -1) continue;
if(x == ed.x && y == ed.y && z == ed.z) return d[p.z][p.x][p.y] + 1;
d[z][x][y] = d[p.z][p.x][p.y] + 1;
q.push({x, y, z});
}
}
return -1;
}
int main()
{
while(cin >> l >> r >> c, l || r || c)
{
for(int i = 0; i < l; ++ i)
for(int j = 0; j < r; ++ j)
for(int k = 0; k < c; ++ k)
{
cin >> g[i][j][k];
if(g[i][j][k] == 'S') st = {j, k, i};
if(g[i][j][k] == 'E') ed = {j, k, i};
}
int res = bfs();
if(res == -1) puts("Trapped!");
else printf("Escaped in %d minute(s).\n", res);
}
return 0;
}