三维BFS
第一次写三维BFS 好爽
没想到bfs模板用熟练了随便写就过了
#include<bits/stdc++.h>
using namespace std;
char a[110][110][110];
int L, R, C;
int vis[110][110][110];
int dx[6] = { 0,0,-1,1,0,0 };
int dy[6] = { -1,1,0,0,0,0};
int dz[6] = { 0,0,0,0,-1,1 };
int sw,sx, sy, ew,ex, ey;
int ans = 0;
struct node {
int w; int x; int y; int foot;
node() {
w = 0; x = 0; y = 0; foot = 0;
}
node(int a,int b,int c,int d) {
w = a; x = b; y = c; foot = d;
}
};
void bfs(int w, int x, int y) {
queue<node> q;
vis[w][x][y] = 1;
q.push(node(w, x, y, 0));
node now;
while (!q.empty()) {
now = q.front();
q.pop();
for (int i = 0; i < 6; i++) {
int xx = now.x + dx[i];
int yy = now.y + dy[i];
int ww = now.w + dz[i];
if (xx < 0 || xx >= R || yy < 0 || yy >= C||ww<0||ww>=L)continue;
if (a[ww][xx][yy] == '#')continue;
if (vis[ww][xx][yy])continue;
if (a[ww][xx][yy] == 'E') {
ans = now.foot + 1;
return;
}
q.push(node(ww, xx, yy, now.foot + 1));
vis[ww][xx][yy] = 1;
}
}
return;
}
int main()
{
while (cin >> L >> R >> C) {
ans = 0x3f3f3f3f;
memset(vis, 0, sizeof(vis));
memset(a, 0, sizeof(a));
if (L == 0 && R == 0 && C == 0) {
break;
}
for (int i = 0; i < L; i++) {
for (int j = 0; j < R; j++) {
cin >> a[i][j];
}
getchar();
}
for (int i = 0; i < L; i++) {
for (int j = 0; j < R; j++) {
for (int k = 0; k < C; k++) {
if (a[i][j][k] == 'S') {
sw = i; sx = j; sy = k;
}
if (a[i][j][k] == 'E') {
ew = i; ex = j; ey = k;
}
}
}
}
bfs(sw, sx, sy);
if (ans == 0x3f3f3f3f)
cout << "Trapped!" << endl;
else cout << "Escaped in " << ans << " minute(s)." << endl;
}
return 0;
}
y总数组实现队列
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 110;
struct Point {
int x, y, z;
};
int L, R, C;
char g[N][N][N];
Point q[N * N * N];
int dist[N][N][N];
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(Point start, Point end) {
int hh = 0, tt = 0;
q[0] = start;
memset(dist, -1, sizeof(dist));
dist[start.x][start.y][start.z] = 0;
while (hh <= tt) {
auto t = q[hh++];
for (int i = 0; i < 6; i++) {
int x = t.x + dx[i];
int y = t.y + dy[i];
int z = t.z + dz[i];
if (x < 0 || x >= L || y < 0 || y >= R || z < 0 || z >= C)
continue;
if (g[x][y][z] == '#')continue;
if (dist[x][y][z] != -1)continue;
dist[x][y][z] = dist[t.x][t.y][t.z] + 1;
if (x == end.x && y == end.y && z == end.z)
return dist[x][y][z];
q[++tt] = { x,y,z };
}
}
return -1;
}
int main() {
while (scanf("%d%d%d", &L, &R, &C), L || R || C) {
Point start, end;
for (int i = 0; i < L; i++) {
for (int j = 0; j < R; j++) {
scanf("%s", g[i][j]);
for (int k = 0; k < C; k++) {
char c = g[i][j][k];
if (c == 'S')
start = { i,j,k };
else if (c == 'E')
end = { i,j,k };
}
}
}
int distance = bfs(start, end);
if (distance == -1)puts("Trapped!");
else printf("Escaped in %d minute(s).\n", distance);
}
return 0;
}