poj2251Dungeon Master bfs

http://poj.org/problem?id=2251

Description

You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides. 

Is an escape possible? If yes, how long will it take? 
Input

The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size). 
L is the number of levels making up the dungeon. 
R and C are the number of rows and columns making up the plan of each level. 
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a '#' and empty cells are represented by a '.'. Your starting position is indicated by 'S' and the exit by the letter 'E'. There's a single blank line after each level. Input is terminated by three zeroes for L, R and C.
Output

Each maze generates one line of output. If it is possible to reach the exit, print a line of the form 
Escaped in x minute(s).

where x is replaced by the shortest time it takes to escape. 
If it is not possible to escape, print the line 
Trapped!
Sample Input

3 4 5
S....
.###.
.##..
###.#

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

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

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

0 0 0
Sample Output

Escaped in 11 minute(s).
Trapped!
#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
char map[50][50][50];
int tx[6]={1,-1, 0, 0, 0, 0};
int ty[6]={0, 0, 1,-1, 0, 0};
int tz[6]={0, 0, 0, 0, 1,-1};
int sx,sy,sz;
int ex,ey,ez;
int n,m,l;//n层,每层m行,l列
struct node
{
 int x;
 int y;
 int z;
 int step;
};
int bfs()
{
 queue<node>q;
 node head,next;
 head.x=sx;
 head.y=sy;
 head.z=sz;
 head.step=0;
 map[head.x][head.y][head.z]='#';//表示这个点已经访问过了,以后不会再访问了
 q.push(head);
 while(!q.empty())
 {
  head=q.front();
  q.pop();
  if(head.x==ex&&head.y==ey&&head.z==ez)
  {
    return head.step;
  }
  for(int i=0;i<6;i++)
  {
   next.x=head.x+tx[i];
   next.y=head.y+ty[i];
   next.z=head.z+tz[i];
   if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&next.z>=0&&next.z<l&&map[next.x][next.y][next.z]!='#')
   {
    next.step=head.step+1;
    map[next.x][next.y][next.z]='#';
    q.push(next);
   }
  }
 }
 return 0;
}
int main()
{
 int i,j,k;
 while(cin>>n>>m>>l&&n&&m&&l)
 {
  for(i=0;i<n;i++)
  {
   for(j=0;j<m;j++)
   {
    cin>>map[i][j];
    for(k=0;k<l;k++)
    {
     if(map[i][j][k]=='S')
     {
      sx=i;
      sy=j;
      sz=k;
     }
     if(map[i][j][k]=='E')
     {
      ex=i;
      ey=j;
      ez=k;
     }
    }
   }
  }
  i=bfs();
  if(i==0)
  cout<<"Trapped!"<<endl;
  else
  cout<<"Escaped in "<<i<<" minute(s)."<<endl;
 }
 return 0;
}

你可能感兴趣的:(poj2251Dungeon Master bfs)