poj 2251 bfs

Time
47ms
Memory
356kB

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
char s[30][30][30];
int d[30][30][30];
int a,b,c,t;
int sx,ex,sy,ey,sz,ez;
int dx[]= {
    
    0,0,0,0,1,-1},dy[]= {
    
    0,0,1,-1,0,0},dz[]= {
    
    1,-1,0,0,0,0};
typedef struct
{
    
    
    int x,y,z;
} P;
int bfs()
{
    
    
    queue<P> q;
    P fri;
    fri.x=sx,fri.y=sy,fri.z=sz;
    q.push(fri);
    d[sx][sy][sz]=0;
    while(q.size()!=0)
    {
    
    
        P fri=q.front();
        q.pop();
        if(fri.x==ex&&fri.y==ey&&fri.z==ez)break;
        for(int i=0; i<6; i++)
        {
    
    
            P next;
            next.x=fri.x+dx[i];
            next.y=fri.y+dy[i];
            next.z=fri.z+dz[i];
            if(next.x>=0 && next.x<a && next.y>=0 && next.y<b && next.z>=0 && next.z<c && d[next.x][next.y][next.z]==-1 && s[next.x][next.y][next.z]!='#')
            {
    
    
                q.push(next);
                d[next.x][next.y][next.z]=d[fri.x][fri.y][fri.z]+1;
            }
        }
    }
    return d[ex][ey][ez];
}
int main()
{
    
    
    while(scanf("%d%d%d",&a,&b,&c)!=EOF,a+b+c)
    {
    
    
        t=0;
        for(int i=0; i<a; i++)
{
    
    
                for(int j=0; j<b; j++)
            {
    
    
                for(int k=0; k<c; k++)
                {
    
    
                    cin>>s[i][j][k];
                    if(s[i][j][k]=='S')
                        sx=i,sy=j,sz=k;
                    if(s[i][j][k]=='E')
                        ex=i,ey=j,ez=k;
                }
            }
            getchar();
}

        memset(d,-1,sizeof d);
//    for(int i=0;i<a;i++)
//    {
    
    
//        for(int j=0;j<b;j++)
//        {
    
    
//            for(int k=0;k<c;k++)
//            {
    
    
//                d[i][j][k]=-1;//初始化为无穷
//            }
//        }
//    }

        int num=bfs();
        if (num!= -1)
            cout<<"Escaped in "<<num<<" minute(s)."<<endl;
        else
            cout<<"Trapped!"<<endl;

    }
}

需要注意的地方是初始点和末端点的坐标带入不要错了。

猜你喜欢

转载自blog.csdn.net/weixin_51626694/article/details/116106463