1096. 地牢大师

在这里插入图片描述
在这里插入图片描述
思路:
三维BFS
由于该题是三维迷宫,所以不使用pair来存储坐标,利用结构体来存储,队列用数组构建也可以使用库函数中的queue来使用,其他方法和二维迷宫操作相同

代码:

# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;

const int N = 110;
struct Point{
    
    
    int x;
    int y;
    int z;
};
char st[N][N][N];
int l,r,c;
int dist[N][N][N];
Point q[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(st[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",st[i][j]);
                for(int t = 0;t < c;t++)
                {
    
    
                    if(st[i][j][t] == 'E')
                    {
    
    
                        end = {
    
    i,j,t};
                    }
                    else if(st[i][j][t] == 'S')
                    {
    
    
                        start = {
    
    i,j,t}; 
                    }
                }
            }
        }
        int distance = bfs(start,end);
        if(distance == -1)
        {
    
    
            printf("Trapped!\n");
        }
        else
        {
    
    
            printf("Escaped in %d minute(s).\n",distance);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45812180/article/details/115049391