Dungeon Master 题解
这道题的题意简单来说:就是在3D迷宫里找出口,也就是三维地图,需要用到三维数组
由于本人写代码极易出错,所以在输入三维数组的时候修改了c(column,即列)的值,重复定义了没看到==,后面改成定义成全局变量就没问题了=
除去粗心大意,这道题也可说是模板题了
这道题的代码dfs部分,写得比较清晰,比较适合初学者理解,因为我也是初学者==,感觉整理的还可哈哈hh~~
好了不多说,上代码叭

附上一张谷歌翻译:

DFS搜索法:
  1 #include<iostream>
  2 #include<queue>
  3 #include<stdio.h>
  4 #include<string.h>
  5 using namespace std;
  6 
  7 int l,r,c,vis[35][35][35];
  8 char mp[35][35][35];
  9 
 10 
 11 int fx[6]={1,0,-1,0,0,0};
 12 int fy[6]={0,1,0,-1,0,0};
 13 int fz[6]={0,0,0,0,1,-1};
 14 
 15 struct node
 16 {
 17     int x,y,z;
 18     int ant;
 19 }now,next,s,e;
 20 
 21 bool check(int x,int y,int z)
 22 {
 23     if(mp[x][y][z]!='#' && !vis[x][y][z] && x>=0 && x<l && y>=0 && y<r && z>=0 && z<c)
 24         return 1;
 25     return 0;
 26 }
 27 
 28 void bfs()
 29 {
 30     queue<node> q;
 31     q.push(s);
 32     while(q.size())
 33     {
 34         now=q.front();
 35         q.pop();        
 36  //       if(now.x==e.x && now.y==e.y && now.z==e.z)
 37          if(mp[now.x][now.y][now.z]=='E') //找到终点E终止
 38         {
 39             return ;
 40         } 
 41         else
 42         {
 43             for(int i=0;i<6;i++)
 44             {
 45                 next.x = now.x+fx[i];//now.x替换了x 
 46                 next.y = now.y+fy[i];
 47                 next.z = now.z+fz[i];
 48                 if(check(next.x,next.y,next.z))
 49                 {
 50                     vis[next.x][next.y][next.z]=1;
 51                     next.ant=now.ant+1;
 52                     q.push(next);
 53                 }
 54             }
 55         }
 56     }
 57 } 
 58 
 59 int main()
 60 {
 61     ios_base::sync_with_stdio(false);
 62     cin.tie(0);
 63     
 64     while(cin>>l>>r>>c && l+r+c)
 65     {
 66         memset(vis,0,sizeof(vis));
 67         memset(mp,0,sizeof(mp));
 68         for(int i=0;i<l;i++)
 69         {
 70             for(int j=0;j<r;j++) 
 71             {
 72                 for(int k=0;k<c;k++)
 73                 {
 74                     cin>>mp[i][j][k];  
 75                     if(mp[i][j][k]=='S') 
 76                     {
 77                         s.x=i;
 78                         s.y=j;
 79                         s.z=k;
 80                         s.ant=0;//直接存入全局变量的结构体 
 81                     } 
 82                     if(mp[i][j][k]=='E') 
 83                     {
 84                         e.x=i;
 85                         e.y=j;
 86                         e.z=k;
 87                     } 
 88                 }
 89             }
 90         }
 91         vis[s.x][s.y][s.z]=1;
 92         bfs();//找路 
 93         if(now.ant)
 94         { 
 95             cout<<"Escaped in "<<now.ant<<" minute(s)."<<endl;
 96         }
 97         else
 98         {
 99             cout<<"Trapped!"<<endl;
100         }
101     }
102     return 0;
103 }
/*都在注释里咯,第一次多指教了~~*/
**

                
            
        
浙公网安备 33010602011771号