poj2251地下城主

来源:互联网 发布:flukeview软件下载 编辑:程序博客网 时间:2024/04/27 23:25

突然感觉自己也是大神诶~~~爽!!!!倍爽!!!!
虽然是个简单题,但是不用模板默写感觉还是很不错的,其实就是个bfs,上代码,一切都在代码里说

#include<cstdio>#include<cstring>#include<queue>#include<algorithm>using namespace std;struct node{    int x , y , z , time;};int dir[6][3] = {{1 , 0 , 0} , {0 , 1 , 0} , {0 , 0 , 1} , {-1, 0 , 0} , {0 , -1 , 0} , {0 , 0 , -1}};int L , W , T ;char map[33][33][33];//厚度,宽度,长度bool flag[33][33][33];int sx , sy , sz , ex , ey , ez;void bfs(){    node tmp , p;    queue<node>q;    // queue empty;    while(!q.empty()){//这个你要把给清空,不然的话会错的,因为以前的没清空        q.pop();    }    p.x = sx;    p.y = sy;    p.z = sz;    p.time = 0;    q.push(p);    flag[sx][sy][sz] = true;//走过就不能再走了    while(!q.empty()){//走到队列一直未空        p = q.front();//取最上面的元素        q.pop();        for(int i = 0 ; i < 6 ; i++){//6个方向,自己去yy            tmp.x = p.x + dir[i][0];            tmp.y = p.y + dir[i][1];            tmp.z = p.z + dir[i][2];            tmp.time = p.time + 1;            if(tmp.x < 0 || tmp.y < 0 || tmp.z < 0 || tmp.x >= T || tmp.y >= W || tmp.z >= L || flag[tmp.x][tmp.y][tmp.z] || map[tmp.x][tmp.y][tmp.z] == '#')                continue;            flag[tmp.x][tmp.y][tmp.z] = true;            if(tmp.x == ex && tmp.y == ey && tmp.z == ez){                printf("Escaped in %d minute(s).\n",tmp.time);                return;            }            //getchar();            //printf("x = %d , y = %d , z = %d ,time = %d\n", tmp.x , tmp.y , tmp.z , tmp.time);            q.push(tmp);        }    }    printf("Trapped!\n");    return;}int main(){    while(~scanf("%d %d %d",&T , &W , &L)){        memset(flag , false , sizeof(flag));        if(T == 0 && W == 0 && L == 0)            break;        for(int i = 0 ; i < T ; i++){            for(int j = 0 ; j < W ; j++)                scanf("%s",map[i][j]);        }        for(int i = 0 ; i < T ; i++){            for(int j = 0 ; j < W ; j++){                for(int 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;                }            }        }        bfs();    }    return 0;}
0 0
原创粉丝点击