POJ - 2251 Dungeon Master(初见三维搜索,还好意思说?!)

题意很简单,给一个起点,给一个终点,不能走障碍物,求最短路径,若到达不了则怎么怎么滴,但是迷宫是三维的!dis数组稍微改一下就好了,wa了两次的原因是忘了清空vis数组。。。队列也得清空

代码

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long LL;
const int mod = 1e9 + 7;
const int maxn = 30 + 10;
char a[maxn][maxn][maxn];
int vis[maxn][maxn][maxn];
int sx, sy, sz;
int fx, fy, fz;
int k, n, m; // k 为层数
int dis[6][3] = {
    {0, 1, 0},  // 本平面右
    {0, 0, 1},  // 去上一个平面
    {1, 0, 0},  // 本平面往下
    {0, -1, 0}, // 本平面往左
    {-1, 0, 0}, // 本平面往上
    {0, 0, -1}, // 去下一个平面
};
struct Node
{
    int x, y, z;
    int step;
};
queue<Node> q;
bool judge(int x, int y, int z)
{
    if (!vis[x][y][z] && (a[x][y][z] != '#') && (z >= 1 && z <= k) && (x >= 1 && x <= n) && (y >= 1 && y <= m))
        return true;
    return false;
}
int BFS()
{
    while (!q.empty())
    {
        Node u = q.front();
        q.pop();
        if (u.x == fx && u.y == fy && u.z == fz)
        {
            return u.step;
        }
        for (int i = 0; i < 6; i++)
        {
            int tx = u.x + dis[i][0];
            int ty = u.y + dis[i][1];
            int tz = u.z + dis[i][2];
            if (judge(tx, ty, tz))
            {
                vis[tx][ty][tz] = 1;
                q.push({tx, ty, tz, u.step + 1});
            }
        }
    }
    return -1;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    // ios::sync_with_stdio(0);
    // cin.tie(0);
    // cout.tie(0);
    while (scanf("%d %d %d", &k, &n, &m) == 3)
    {
        if (k == 0 && n == 0 && m == 0)
            break;
        memset(vis, 0, sizeof vis);
        while (!q.empty())
            q.pop();
        for (int p = 1; p <= k; p++)
            for (int i = 1; i <= n; i++)
                for (int j = 1; j <= m; j++)
                {
                    scanf(" %c", &a[i][j][p]);
                    if (a[i][j][p] == 'S')
                        sx = i, sy = j, sz = p;
                    if (a[i][j][p] == 'E')
                        fx = i, fy = j, fz = p;
                }
        q.push({sx, sy, sz, 0});
        vis[sx][sy][sz] = 1;
        int ans = BFS();
        if (ans == -1)
            printf("Trapped!\n");
        else
            printf("Escaped in %d minute(s).\n", ans);
    }
    return 0;
}
发布了64 篇原创文章 · 获赞 24 · 访问量 8068

猜你喜欢

转载自blog.csdn.net/qq_44115065/article/details/104139653