一、内容

题意:给定一个3D的图,你能走6个方向,问从起点到终点最少的步数。

二、思路

  • bfs搜索一下。

三、代码

#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std; 
int l, r, c, sl, sx, sy;
char g[35][35][35], vis[35][35][35];
int dx[6] = {-1, 1, 0, 0, 0, 0};
int dy[6] = {0, 0, -1, 1, 0, 0}; 
int dl[6] = {0, 0, 0, 0, 1, -1};
struct node {
	int l, x, y, step;
	node (int l, int x, int y, int step): l(l), x(x), y(y), step(step){}
};
bool ok(int fl, int fx, int fy) {
	if (fl < 0 || fx < 0 || fy < 0 || fl >= l || fx >= r || fy >= c || g[fl][fx][fy] == '#') return false;
	return true;
}
int bfs() {
	queue<node> q;
	q.push(node(sl, sx, sy, 0));
	while (!q.empty()) {
		node t = q.front();
		q.pop();
		if (g[t.l][t.x][t.y] == 'E') return t.step;
		if (vis[t.l][t.x][t.y]) continue;
		vis[t.l][t.x][t.y] = 1;
		//6个方向
		for (int i = 0; i < 6; i++) {
			int fl = t.l + dl[i];
			int fx = t.x + dx[i];
			int fy = t.y + dy[i];
			if (ok(fl, fx, fy)) {
				q.push(node(fl, fx, fy, t.step + 1));
			}
		} 
	}
	return -1;
}
int main() {
	while (scanf("%d%d%d", &l, &r, &c), l) {
		memset(vis, 0, sizeof(vis));
		for (int i = 0; i < l; i++) {
			for (int j = 0; j < r; j++) {
				scanf("%s", g[i][j]);
			}
		}
		for (int i = 0; i < l; i++) {
			for (int j = 0; j < r; j++) {
				for (int k = 0; k < c; k++) {
					if (g[i][j][k] == 'S') {
						sl = i, sx = j, sy = k;
						break;
					}
				}
			}
		}		
		int step = bfs();
		if (step == -1) {
			printf("Trapped!\n");
		} else {
			printf("Escaped in %d minute(s).\n", step);
		}
	}
	return 0;
}