poj 2251 Dungeon Master (bfs)

刷水题好爽!但是别真跟xcy说的一样,把rp都给用完了...

三维空间的bfs,只是搜索的时候多了两个方向而已。

code:

#include<cstdio>
#include<cstring>
bool vis[31][31][31] ;
int lve[6] = {10000, -1} ;
int row[6] = {0, -10010} ;
int col[6] = {00, -1100} ;
bool flag ;
int a, b, c ;
struct node{
    int x ;
    int y ;
    int z ;
    int step ;
}q[1000000] ;
node s, e ;
bool in(node t){
    if(t.x>=0&&t.x<a&&t.y>=0&&t.y<b&&t.z>=0&&t.z<c) return true ;
    return false ;
}
void bfs(){
    int h, r ;
    h = 0 ;
    r = 1 ;
    q[0] = s ;
    int j=0 ;
    while(r>h){
        node p = q[h++] ;
        for(int i=0; i<6; i++){
            node temp = p ;
            temp.x += lve[i] ;
            temp.y += row[i] ;
            temp.z += col[i] ;
            if(in(temp)&&!vis[temp.x][temp.y][temp.z]){
                if(temp.x==e.x&&temp.y==e.y&&temp.z==e.z){
                    printf("Escaped in %d minute(s).\n", temp.step+1) ;
                    flag = true ;
                    return ;
                }
                vis[temp.x][temp.y][temp.z] = true ;
                temp.step ++ ;
                q[r++] = temp ;
            }
        }
    }
}
int main(){
    int i, j, k ;
    char str[31] ;
    while(~scanf("%d%d%d", &a, &b, &c)&&(a+b+c)){
        memset(vis, falsesizeof(vis)) ;
        for(i=0; i<a; i++){
            for(j=0; j<b; j++){
                getchar() ;
                scanf("%s", str) ;
                for(k=0; k<c; k++){
                    if(str[k]=='S'){
                        s.x = i ;
                        s.y = j ;
                        s.z = k ;
                        s.step = 0 ;
                        vis[i][j][k] = true ;
                    }else if(str[k]=='E'){
                        e.x = i ;
                        e.y = j ;
                        e.z = k ;
                    }else if(str[k]=='#')
                        vis[i][j][k] = true ;
                }
            }
        }
        flag = false ;
        bfs() ;
        if(!flag)   printf("Trapped!\n") ;
    }
    return 0 ;

原文地址:https://www.cnblogs.com/xiaolongchase/p/2353510.html