您的位置:首页 > 其它

BFS POJ 2251 Dungeon Master

2015-08-02 13:14 399 查看
题目传送门

 /*
BFS:这题很有意思,像是地下城,图是立体的,可以从上张图到下一张图的对应位置,那么也就是三维搜索,多了z坐标轴
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;

const int MAXN = 33;
const int INF = 0x3f3f3f3f;
struct Point    {
int x, y, z, step;
};
char maze[MAXN][MAXN][MAXN];
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};
bool vis[MAXN][MAXN][MAXN];
int l, r, c;

bool judge(int x, int y, int z) {
if (x < 1 || x > r || y < 1 || y > c || z < 1 || z > l || vis[z][x][y] || maze[z][x][y] == '#') return false;
return true;
}

void BFS(void)  {
int sx, sy, sz, ex, ey, ez;
for (int i=1; i<=l; ++i)    {
for (int j=1; j<=r; ++j)    {
for (int k=1; k<=c; ++k)    {
if (maze[i][j][k] == 'S')   {
sx = j; sy = k; sz = i;
}
else if (maze[i][j][k] == 'E')  {
ex = j; ey = k; ez = i;
}
}
}
}
memset (vis, false, sizeof (vis));
queue<Point> Q; Q.push ((Point) {sx, sy, sz, 0});
bool flag = false;  vis[sz][sx][sy] = true;
while (!Q.empty ()) {
Point p = Q.front ();   Q.pop ();
if (p.x == ex && p.y == ey && p.z == ez)  {
printf ("Escaped in %d minute(s).\n", p.step);
flag = true;    break;
}
for (int i=0; i<6; ++i) {
int tx = p.x + dx[i];   int ty = p.y + dy[i];   int tz = p.z + dz[i];
if (judge (tx, ty, tz)) {
vis[tz][tx][ty] = true;
Q.push (Point {tx, ty, tz, p.step + 1});
}
}
}
if (!flag)  puts ("Trapped!");
}

int main(void)  {       //POJ 2251 Dungeon Master
while (scanf ("%d%d%d", &l, &r, &c) == 3)   {
if (!l && !r && !c) break;
for (int i=1; i<=l; ++i)    {
for (int j=1; j<=r; ++j)    scanf ("%s", maze[i][j] + 1);
}
BFS ();
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: