poj2251 Dungeon Master bfs

来源:互联网 发布:人造暖男网络电影上映 编辑:程序博客网 时间:2024/04/25 12:12

题目链接:http://poj.org/problem?id=2251

题目大意: 

给出一三维空间的地牢,要求求出由字符'S'到字符'E'的最短路径

移动方向可以是上,下,左,右,前,后,六个方向

每移动一次就耗费一分钟,要求输出最快的走出时间。

不同L层的地图,相同RC坐标处是连通的

 

简单的bfs

///2014.3.30 - 2014.4.2///poj2251#include <iostream>#include <cstdio>using namespace std;int L,R,C;char maze[40][40][40];bool visted[40][40][40];struct position{    char l,r,c;  ///由于l,r,c均小于40,这里把char当作单字节整数用    int step;};position s,e;int addR[6] = {-1,0,1,0,0,0};int addC[6] = {0,-1,0,1,0,0};int addL[6] = {0,0,0,0,1,-1};void init(){    char temp;    for(int i=1 ; i<=L ; i++){        for(int j=1 ; j<=R ; j++){            for(int k=1 ; k<=C ; k++){                cin>>temp;                if( temp == 'S' ){                    s.l=i , s.r=j , s.c=k ,s.step=0 ;                }                if( temp == 'E' ){                    temp = '.';                    e.l=i , e.r=j , e.c=k ,e.step=-1;                }                maze[i][j][k] = temp;                visted[i][j][k] = false;            }        }    }}int bfs(position pos){    position queue[30000];    int head,tail;    queue[0] = pos;    queue[0].step = 0;    visted[pos.l][pos.r][pos.c] = true;    head = 0;    tail = 1;    bool find = false;    while( head<tail && !find ){        for(int i=0 ; i<6 ; i++){            if( queue[head].l+addL[i]>=1 && queue[head].l+addL[i]<=L &&                    queue[head].r+addR[i]>=1 && queue[head].r+addR[i]<=R &&                    queue[head].c+addC[i]>=1 && queue[head].c+addC[i]<=C &&                    !visted[ queue[head].l+addL[i] ][ queue[head].r+addR[i] ][ queue[head].c+addC[i] ] &&                     maze[ queue[head].l+addL[i] ][ queue[head].r+addR[i] ][ queue[head].c+addC[i] ]=='.' ){                queue[tail].l = queue[head].l + addL[i];                queue[tail].r = queue[head].r + addR[i];                queue[tail].c = queue[head].c + addC[i];                queue[tail].step = queue[head].step + 1;                visted[ queue[tail].l ][ queue[tail].r ][ queue[tail].c ] = true;                if( queue[tail].l==e.l && queue[tail].r==e.r && queue[tail].c==e.c ){                    find = true;                    break;                }                tail++;            }        }        head++;    }        if( find ){        return queue[tail].step;    }    else        return -1;}int main(){    // freopen("in","r",stdin);    // freopen("out","w",stdout);    while( cin>>L>>R>>C && L && R && C ){        init();        int time = bfs(s);        if( time==-1 )            cout<<"Trapped!"<<endl;        else            cout<<"Escaped in "<<time<<" minute(s)."<<endl;    }    return 0;}

0 0
原创粉丝点击