Dungeon Master 题解

这道题的题意简单来说:就是在3D迷宫里找出口,也就是三维地图,需要用到三维数组

由于本人写代码极易出错,所以在输入三维数组的时候修改了c(column,即列)的值,重复定义了没看到==,后面改成定义成全局变量就没问题了=

除去粗心大意,这道题也可说是模板题了

这道题的代码dfs部分,写得比较清晰,比较适合初学者理解,因为我也是初学者==,感觉整理的还可哈哈hh~~

好了不多说,上代码叭

 DFS搜索法:

#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;

int l,r,c,vis[35][35][35];
char mp[35][35][35];


int fx[6]={1,0,-1,0,0,0};
int fy[6]={0,1,0,-1,0,0};
int fz[6]={0,0,0,0,1,-1};

struct node
{
    int x,y,z;
    int ant;
}now,next,s,e;

bool check(int x,int y,int z)
{
    if(mp[x][y][z]!='#' && !vis[x][y][z] && x>=0 && x<l && y>=0 && y<r && z>=0 && z<c)
        return 1;
    return 0;
}

void bfs()
{
    queue<node> q;
    q.push(s);
    while(q.size())
    {
        now=q.front();
        q.pop();        
 //       if(now.x==e.x && now.y==e.y && now.z==e.z)
         if(mp[now.x][now.y][now.z]=='E') //找到终点E终止
        {
            return ;
        } 
        else
        {
            for(int i=0;i<6;i++)
            {
                next.x = now.x+fx[i];//now.x替换了x 
                next.y = now.y+fy[i];
                next.z = now.z+fz[i];
                if(check(next.x,next.y,next.z))
                {
                    vis[next.x][next.y][next.z]=1;
                    next.ant=now.ant+1;
                    q.push(next);
                }
            }
        }
    }
} 

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    while(cin>>l>>r>>c && l+r+c)
    {
        memset(vis,0,sizeof(vis));
        memset(mp,0,sizeof(mp));
        for(int i=0;i<l;i++)
        {
            for(int j=0;j<r;j++) 
            {
                for(int k=0;k<c;k++)
                {
                    cin>>mp[i][j][k];  
                    if(mp[i][j][k]=='S') 
                    {
                        s.x=i;
                        s.y=j;
                        s.z=k;
                        s.ant=0;//直接存入全局变量的结构体 
                    } 
                    if(mp[i][j][k]=='E') 
                    {
                        e.x=i;
                        e.y=j;
                        e.z=k;
                    } 
                }
            }
        }
        vis[s.x][s.y][s.z]=1;
        bfs();//找路 
        if(now.ant)
        { 
            cout<<"Escaped in "<<now.ant<<" minute(s)."<<endl;
        }
        else
        {
            cout<<"Trapped!"<<endl;
        }
    }
    return 0;
}

/*都在注释里咯,第一次多指教了~~*/

**

猜你喜欢

转载自www.cnblogs.com/Ilaria/p/12228501.html