2251POJ

这道题的意思是有让你从S点到E点,求出最短距离,当时这个最短距离是在三维情况下搜索,我们用了一个上下左右,上一层,下一层这六个方向的方向数组,来进行BFS,就可以求出来了。

int dir[6][3]= {-1,0,0,1,0,0,0,-1,0,0,1,0,0,0,-1,0,0,1};
当然了,标记数组也要是三维的所以是 int vis[31][31][31];

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

int vis[31][31][31];
string mp[109][109];
int dir[6][3]= {-1,0,0,1,0,0,0,-1,0,0,1,0,0,0,-1,0,0,1};
int c,l,r;
int sum;
int sd,sx,sy;


struct node
{
    int d,x,y;
    int cnt;
} e,s,v,u;
queue<node>Q;
void bfs()
{

    s.d = sd;
    s.x = sx;
    s.y = sy;
    //cout<<s.d<<" "<<s.x<<" "<<s.y<<" "<<s.cnt<<endl;
    s.cnt = 0;
    while(!Q.empty())Q.pop();
    Q.push(s);
    int flag = 0;
    while(!Q.empty())
    {
        u  = Q.front();
        //cout<<u.d<<" "<<u.x<<" "<<u.y<<endl;
        Q.pop();
        for(int i = 0; i<6; i++)//三维六个方向
        {
            int dd = u.d + dir[i][0];
            int xx = u.x + dir[i][1];
            int yy = u.y + dir[i][2];
            if(dd>=0&&dd<c&&xx>=0&&xx<l&&yy>=0&&yy<r&&!vis[dd][xx][yy]&&mp[dd][xx][yy]!='#')
            {
                vis[dd][xx][yy] = 1;
                v.d = dd;
                v.x = xx;
                v.y = yy;
                v.cnt = u.cnt + 1;
                Q.push(v);
                if(mp[dd][xx][yy]=='E')
                {
                    //cout<<"TEST"<<endl;
                    sum=u.cnt+1;
                    return;
                }
            }
        }
    }
}
int main()
{
    //freopen("ans.txt","r", stdin);
    while(~scanf("%d%d%d",&c,&l,&r))
    {
        if(c==0&&l==0&&r==0)break;
        for (int i = 0; i < c; ++i)
        {
            for (int j = 0; j < l; ++j)
            {
                cin>>mp[i][j];
                for (int k = 0; k < mp[i][j].size(); ++k)
                {
                    if (mp[i][j][k] == 'S')
                    {
                        sd = i;
                        sx = j;
                        sy = k;
                    }
                }
            }
        }
        //cout<<s.d<<" "<<s.x<<" "<<s.y<<" "<<s.cnt<<endl;
        memset(vis,0,sizeof(vis));
        sum = -1;
        vis[s.d][s.x][s.y] = 1;
        bfs();
        if(sum==-1)
        {
            puts("Trapped!");
        }
        else
        {
            printf("Escaped in %d minute(s).\n",sum);
        }
    }
    return 0;
}


你可能感兴趣的:(2251POJ)