UESTC_王之迷宫 2015 UESTC Training for Search Algorithm & String<Problem A>

A - 王之迷宫

Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
 

王被困在了一个3维的迷宫中,他很想逃离这个迷宫回去当学霸,你能帮助他么? 由于王很仁慈,他悄悄地告诉你,本题读入迷宫的每一行时,要用scanf("%s"...) ......

Input

多组测试数据,对于每组测试数据,有三个整数 L,R,C0<l,r,c30)。

L代表迷宫的高度,RC分别代表每一层的行和列。

接下来是LR×C的矩阵,矩阵包含4种字符(S,E,.,#),S代表王的初始位置,E代表出口,#代表障碍。.代表能通过的地方。

每一层之后有一个空行。

L=R=C=0时,输入中断。

Output

如果可以逃离迷宫,按下列格式输出最短时间:

Escaped in x minute(s). (x表示逃离迷宫的最短时间, 走一步花费一昏钟)

否则,输出:

Trapped!

Sample input and output

Sample InputSample Output
3 4 5
S....
.###.
.##..
###.#

#####
#####
##.##
##...

#####
#####
#.###
####E

1 3 3
S##
#E#
###

0 0 0
Escaped in 11 minute(s).
Trapped!

解题报告:

 简单bfs,直接跑就完了

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
char g[40][40][40];
bool vis[40][40][40];
int l,r,c;
int dir[6][3] = {-1,0,0,1,0,0,0,-1,0,0,1,0,0,0,-1,0,0,1};
typedef struct status
{
  int x,y,z,step;
  status(const int &x,const int &y,const int &z,const int &step)
   {
         this->x  = x , this->y = y, this->z = z ,this->step = step;
   }
};

queue<status>q;
int tarx,tary,tarz;

bool judge(int x,int y,int z)
{
   if (g[z][x][y] == '#' || x >= r || x < 0 || y >= c || y < 0 || z >= l || z < 0)
    return false;
   return true;
}

int bfs()
{
   while(!q.empty())
    {
        status ns = q.front();q.pop();
        if (ns.x == tarx && ns.y == tary && ns.z == tarz)
         return ns.step;
        int x = ns.x , y = ns.y , z = ns.z , step = ns.step;
        for(int i = 0 ; i < 6 ; ++ i)
         {
             int newx = x + dir[i][0];
             int newy = y + dir[i][1];
             int newz = z + dir[i][2];
             if(!judge(newx,newy,newz) || vis[newx][newy][newz])
              continue;
             vis[newx][newy][newz] = true;
             q.push(status(newx,newy,newz,step+1));
         }
    }
   return -1;
}

int main(int argc,char *argv[])
{
  while(scanf("%d%d%d",&l,&r,&c)  && l )
   {
         for(int i = 0 ; i < l ; ++ i)
          for(int j = 0 ; j < r ; ++ j)
           scanf("%s",g[i][j]);
         int stx,sty,stz;
         for(int i = 0 ; i < l ; ++ i)
          for(int j = 0 ; j < r ; ++ j)
           for(int k = 0 ; k < c ; ++ k)
            {
                if (g[i][j][k] == 'S')
                 stx = j,sty = k,stz = i;
                if (g[i][j][k] == 'E')
                 tarx = j,tary = k , tarz = i;
         }
      while(!q.empty())
       q.pop();
      memset(vis,false,sizeof(vis));
      vis[stx][sty][stz] = true;
      q.push(status(stx,sty,stz,0));
      int ans = bfs();
      if (ans != -1)
       printf("Escaped in %d minute(s).
",ans);
      else
       printf("Trapped!
");
   }
  return 0;
}
No Pain , No Gain.
原文地址:https://www.cnblogs.com/Xiper/p/4497036.html