POJ2251 Dungeon Master

Dungeon Master

点击查看题目



三维搜索
求最短路用BFS(DFS很可能会超时)
搜索过程中注意标记, 防止搜过的结点再次被搜索, 造成超时

 #include<cstdio>
#include<queue>
#include<cstring>

using namespace std;

struct node
{
    int x, y, z, num;
}s, e;


int l, r, c;
int dirx[6]={1, -1, 0, 0, 0, 0};
int diry[6]={0, 0, 1, -1, 0, 0};
int dirz[6]={0, 0, 0, 0, 1, -1};
bool visit[35][35][35]={0}, flag;
node temp, se;


void bfs()
{
    queue<node>q;
    s.num=0;
    q.push(s);
    while(!q.empty())
    {
        temp = q.front();
        visit[temp.x][temp.y][temp.z]=0;
        q.pop();
        if(temp.x==e.x && temp.y == e.y && temp.z ==e.z)
        {
            flag=1;
            return ;
        }
        for(int i=0; i<6; i++)
        {
            se.x=temp.x+dirx[i];
            se.y=temp.y+diry[i];
            se.z=temp.z+dirz[i];
            se.num=temp.num+1;
            if(visit[temp.x+dirx[i]][temp.y+diry[i]][temp.z+dirz[i]]==1 && se.x<l && se.y<r && se.z<c && se.x>=0 && se.y>=0 && se.z>=0)
            {
                visit[se.x][se.y][se.z]=0;
                q.push(se);
            }
        }
    }
    return ;
}

int main()
{
    while(~scanf("%d%d%d", &l, &r, &c))
    {
        if(l==0 && r==0 && c==0)
            break;
        getchar();
        for(int i=0; i<l; i++)
        {
            for(int j=0; j<r; j++)
            {
                for(int k=0; k<c; k++)
                {
                    char temp;
                    scanf("%c", &temp);
                    if(temp=='#')
                    {
                        visit[i][j][k]=0;
                    }
                    else if(temp=='.')
                    {
                        visit[i][j][k]=1;
                    }
                    else if(temp=='S')
                    {
                        s.x = i;
                        s.y = j;
                        s.z = k;
                    }
                    else if(temp=='E')
                    {
                        e.x = i;
                        e.y = j;
                        e.z = k;
                        visit[i][j][k]=1;
                    }
                }
                getchar();
            }
            getchar();
        }
        flag=0;
        bfs();
        if(flag)
            printf("Escaped in %d minute(s).\n", temp.num);
        else
            printf("Trapped!\n");
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/liudazhuang98/article/details/81237126