NYOJ3533D dungeon

题目链接: http://acm.nyist.net/JudgeOnline/problem.php?pid=353

BFS+优先队列

代码:

#include 
#include 
#include 

using namespace std;

int l,r,c;
int stx,sty,stz;
int enx,eny,enz;
bool flag;
struct M{
   char s[35][35];
}a[35];
typedef struct node{
   int x,y,z;
   int step;
}node;
node t,temp;
int v[35][35][35];

struct cmp{
    bool operator()(node x,node y)
    {
        return x.step > y.step;
    }
};
int dx[] = {-1,0,1,0,0,0};
int dy[] = {0,1,0,-1,0,0};
int dz[] = {0,0,0,0,1,-1};

void bfs()

{
    node start;
    priority_queue,cmp> q;
    start.x = stx;
    start.y = sty;
    start.z = stz;
    start.step = 0;
    q.push(start);
    while(!q.empty())
    {
        temp = q.top();
        q.pop();
        for(int i = 0;i < 6;++i)
        {

            //printf("%d %d %d\n",temp.x,temp.y,temp.z);
            if(temp.x == enx && temp.y == eny && temp.z == enz)
            {
                printf("Escaped in %d minute(s).\n",temp.step);
                flag = true;
                return ;
            }

            t.x = temp.x + dx[i];
            t.y = temp.y + dy[i];
            t.z = temp.z + dz[i];
            t.step = temp.step + 1;
            if(t.x >= 0 && t.x < r && t.y >= 0 && t.y < c && t.z >= 0 && t.z < l && !v[t.x][t.y][t.z] && a[t.z].s[t.x][t.y] != '#')
            {
                v[t.x][t.y][t.z] = 1;
                q.push(t);

            }
        }
    }
}

int main()

{
    while(~scanf("%d%d%d",&l,&r,&c))
    {
        if(!l && !r && !c)
            break;
        memset(v,0,sizeof(v));
        for(int i = 0;i < l;++i)
        {
            for(int j = 0;j < r;++j)
                scanf("%s",a[i].s[j]);
        }
        for(int i = 0;i < l;++i)
        {
            for(int j = 0;j < r;++j)
            {
                for(int k = 0;k < c;++k)
                    if(a[i].s[j][k] == 'S')
                {
                       stz = i;
                       stx = j;
                       sty = k;
                }
                else if(a[i].s[j][k] == 'E')
                {
                    enz = i;
                    enx = j;
                    eny = k;
                }
            }
        }
        v[stx][sty][stz] = 1;
        flag = false;
        bfs();
        if(!flag)
            printf("Trapped!\n");
    }
    return 0;
}

你可能感兴趣的:(bfs)