題目:
你被困在一個3D地牢中且繼續尋找最短路徑逃生!地牢由立方體單位構成,立方體單位中有的會充滿岩石。向上下前后左右移動一個單位需要一分鍾。你不能向對角線的四個方向移動且迷宮四周環繞着許多岩石。
是否可以逃出地牢?如果可以,則需要多少時間?
輸入:
輸入的第一行包含一個數,表示地牢的數量。
每個地牢的描述,其第一行包含三個數L,R和C(均小於等於30)。
L表示地牢的層數;R和C分別表示每層地牢的行與列的大小。
隨后輸入地牢的層數L,每層中包含R行,每行中包含C個字符。
每個字符表示地牢的一個單元。'#'表示岩石單元,'.'表示空白單元。你的起始位置在點'S',出口為'E'。
每層地牢的輸入后都有一個空行。當L,R和C均為0時,輸入結束。
輸出:
每個迷宮對應一行輸出。
如果可以逃生,則輸出如下
Escaped in x minute(s).
x為最短脫離時間。
如果無法逃生,則輸出如下
Trapped!
樣例:
分析:BFS模板題,只不過二維變成三維,注意把出口視為可通過
ac代碼如下:
#include<iostream> #include<sstream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> #include<functional> #include<iomanip> #include<numeric> #include<cmath> #include<queue> #include<vector> #include<set> #include<cctype> #define PI acos(-1.0) const int INF = 0x3f3f3f; const int NINF = -INF - 1; typedef long long ll; using namespace std; int L, R, C; struct Maze { int x, y, z; }m; char maze[35][35][35]; int d[35][35][35]; int sx, sy, sz, ex, ey, ez; int dx[6] = {1, -1, 0, 0, 0, 0}, dy[6] = {0, 0, 1, -1, 0, 0}, dz[6] = {0, 0, 0, 0, 1, -1}; int bfs() { queue <Maze> q; for (int i = 0; i < L; ++i) { for (int j = 0; j < R; ++j) { for (int k = 0; k < C; ++k) d[i][j][k] = INF; } } d[sx][sy][sz] = 0; m.x = sx, m.y = sy, m.z = sz; q.push(m); while (q.size()) { Maze temp = q.front(); q.pop(); if (temp.x == ex && temp.y == ey && temp.z == ez) break; for (int i = 0; i < 6; ++i) { int nx = temp.x + dx[i], ny = temp.y + dy[i], nz = temp.z + dz[i]; if ((nx >= 0 && nx < L) && (ny >= 0 && ny < R) && (nz >= 0 && nz < C) && d[nx][ny][nz] == INF && maze[nx][ny][nz] != '#') { Maze ans; ans.x = nx, ans.y = ny, ans.z = nz; q.push(ans); d[nx][ny][nz] = d[temp.x][temp.y][temp.z] + 1; } } } return d[ex][ey][ez]; } int main() { while (cin >> L >> R >> C) { if (L == 0 && R == 0 && C == 0) break; for (int i = 0; i < L; ++i) { for (int j = 0; j < R; ++j) { for (int k = 0; k < C; ++k) { cin >> maze[i][j][k]; if (maze[i][j][k] == 'S') sx = i, sy = j, sz = k; if (maze[i][j][k] == 'E') ex = i, ey = j, ez = k; } } getchar(); } int num = bfs(); if (num != INF) cout << "Escaped in " << num << " minute(s)." << endl; else cout << "Trapped!" << endl; } return 0; }