三维数组BFS

水题,就是要求在三维迷宫里找到最短路

#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <queue>
using namespace std;
const int INF=1000000;
char maze[35][35][35];
int n,m,k;
int sy,sx,sz;
int ex,ey,ez;
int d[35][35][35];
int to[6][3] = {{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
struct Node{
int x,y,z,leng
};
int check(int x,int y,int z)
{
    if(x<0 || y<0 || z<0 || x>=k || y>=n || z>=m)
        return 1;
    else if(maze[x][y][z] == '#')
        return 1;
    else if(d[x][y][z]==INF)
        return 1;
    return 0;
}
int bfs()
{
    int i;
    Node a,next;
    queue<Node> tang;
    a.x = sx,a.y = sy,a.z = sz;
    a.leng = 0;
    d[sx][sy][sz] = INF;
    tang.push(a);
    while(!tang.empty())
    {
        a=tang.front();
        tang.pop();
        if(a.x==ex&&a.y==ey&&a.z==ez)
            return a.leng;
        for(i=0; i<6; i++)
        {
            next=a;
            next.x=a.x+to[i][0];
            next.y=a.y+to[i][1];
            next.z=a.z+to[i][2];
            if(check(next.x,next.y,next.z))
            {
                continue;
            }
            d[next.x][next.y][next.z]=INF;
            next.leng=a.leng+1;
            tang.push(next);
        }
    }
    return 0;
}
int main()
{
    while(~scanf("%d%d%d",&k,&n,&m))
    {
        if(k==0&&n==0&&m==0) break;
        for(int i=0; i<k; i++)
            for(int j=0; j<n; j++)
            {
                scanf("%s",maze[i][j]);
                for(int f = 0; f<m; f++)
                {
                    if(maze[i][j][f] == 'S')
                    {
                        sx = i,sy = j,sz = f;
                    }
                    else if(maze[i][j][f] == 'E')
                    {
                        ex = i,ey = j,ez = f;
                    }
                }
            }
        memset(d,0,sizeof(d));
        int tme;
        tme=bfs();
        if(tme)
        {
            cout<<"Escaped in "<<tme<<" minute(s)."<<endl;
        }
        else
        {
            cout<<"Trapped!"<<endl;
        }
    }
    return 0;
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务