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

题意 : 就是迷宫升级版,从以前的一个矩阵也就是一层,变为现在的L层," . "是可以走,但是“#”不可以走,从S走到E,求最短的路径,若是找不到就输出“Trapped!”,每一层的同一个位置若都是" . "是可以直接走的,换句话说,map[1][j][k]与map[2][j][k]若都是" . ",是可以从map[1][j][k]走到map[2][j][k]的

思路 : 求最短路径,用BFS ,这个题比较搞,分类在DFS里,但用DFS会超时啊,所以倒是欺骗了不少童鞋,这个题我没写不出来,会神说用3维的东南西北上下,六个方向进行搜索即可,好吧,好麻烦

#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std ;
const int maxn = 70 ;
char map[maxn][maxn][maxn] ;
int vis[maxn][maxn][maxn] ;
struct node
{
    int x,y,z;
    int step ;
}ch,sh ;
int floor,row,col ;
int s[7][4] = {{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}} ;
//存的方向,分别为上,下,东,西,北,南代表6个方向,里边的3个元素分别为z轴,x轴,y轴
int ex,ey,ez ;
int stepp,zz,xx,yy;
int sx,sy,sz;
void bfs(int x,int y,int z)
{
    queue<node>Q;
    ch.x = x ;
    ch.y = y ;
    ch.z = z ;
    ch.step = 0 ;//初始化
    Q.push(ch) ;//入队列
    vis[z][x][y] = 1 ;//标记为1
    while(!Q.empty())
    {
        sh = Q.front() ;
        Q.pop();
        if(sh.x == ex&&sh.y == ey&&sh.z == ez)
        {
            stepp = sh.step ;//如果到了E点,就把步数保存下来,并返回
            return ;
        }
        for(int i = 0 ; i < 6 ; i++)//东南西北上下六个方向进行搜索
        {
            zz = sh.z+s[i][0] ;
            xx = sh.x+s[i][1] ;
            yy = sh.y+s[i][2] ;
            if(zz>=0&&xx>=0&&yy>=0&&zz<floor&&xx<row&&yy<col&&map[zz][xx][yy]!= '#'&&!vis[zz][xx][yy])
            {//找到没有出边界的,不是'#'的,并且未被访问过的就进行入队操作
                ch.x = xx ;
                ch.y = yy ;
                ch.z = zz ;
                ch.step = sh.step+1;
                Q.push(ch) ;
                vis[zz][xx][yy] = 1 ;//标记这个点为已访问
            }
        }
    }
}
int main()
{
    while(~scanf("%d %d %d",&floor,&row,&col))
    {
        
        if(floor == 0&& row == 0&&col == 0)
        break ;
        stepp = 0 ;
        memset(vis,0,sizeof(vis)) ;
        for(int i = 0 ; i < floor ; i++)
        {
            for(int j = 0 ; j < row ; j++)
            {
                cin>>map[i][j] ;
                getchar();
                for(int k = 0 ; k < col ; k++)
                {
                    if(map[i][j][k] == 'S')//把S点的坐标保存下来
                    {
                        sz = i ;
                        sx = j ;
                        sy = k ;
                    }
                    if(map[i][j][k] == 'E')
                    {
                        ez = i ;
                        ex = j ;
                        ey = k ;
                    }
                }
            }
        }
        bfs(sx,sy,sz) ;
        if(stepp == 0)
        cout<<"Trapped!"<<endl ;
        else
        cout<<"Escaped in "<<stepp<<" minute(s)."<<endl ;
    }
    return 0 ;
}
View Code

 

posted on 2013-08-26 19:00  枫、  阅读(193)  评论(0编辑  收藏  举报