poj 2157 Maze (bfs)

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

算是细节比较多的搜索题了吧,考虑的时间比较长,最终代码写的也是那么的纠结。。。去真的不知道为什么RE啊!重新敲了一遍,完全一样的思路,然后就A掉了!搞毛啊?!白白浪费一下午找bug啊...

#include<cstdio>
#include<cstring>
int key[6], temkey[6] ;
int tur[4][2] = {010, -110, -10} ;
bool vis[21][21] ;
char map[21][21] ;
int n, m, sx, sy ;
struct node{
    int x, y ;
}q[500], door[6] ;
bool bfs(){
    int h, r, dh, dr ;
    h = r = dh = dr = 0 ;
    q[r].x = sx ;
    q[r++].y = sy ;
    vis[sx][sy] = true ;
    while(h<r){
        dh = 0 ;
        node p = q[h++] ;
        for(int i=0; i<4; i++){
            node t = p ;
            t.x += tur[i][0] ;
            t.y += tur[i][1] ;
            if(t.x<0||t.y<0||t.x>=n||t.y>=m||vis[t.x][t.y]||map[t.x][t.y]=='X')
                continue ;
            if(map[t.x][t.y]>='A'&&map[t.x][t.y]<='E'){
                door[dr++] = t ;
                continue ;
            }
            if(map[t.x][t.y]=='G')
                return true ;
            if(map[t.x][t.y]>='a'&&map[t.x][t.y]<='e')
                temkey[map[t.x][t.y]-'a'] ++ ;
            q[r++] = t ;
            vis[t.x][t.y] = true ;
        }
        if(h==r){
            while(dh<dr){
                p = door[dh] ;
                if(key[map[p.x][p.y]-'A']==temkey[map[p.x][p.y]-'A']){
                    q[r++] = p ;
                    vis[p.x][p.y] = true ;
                    for(int i=dh; i<dr; i++)
                        door[i] = door[i+1] ;
                    dr -- ;
                }
                dh ++ ;
            }
        }
    }
    return false ;
}
int main(){
    int i, j ;
    while(~scanf("%d%d", &n, &m)&&n+m){
        memset(key, 0sizeof(key)) ;
        memset(temkey, 0sizeof(temkey)) ;
        memset(vis, falsesizeof(vis)) ;
        for(i=0; i<n; i++){
            getchar() ;
            scanf("%s", map[i]) ;
            for(j=0; j<m; j++){
                if(map[i][j]=='S')  sx = i, sy = j ;
                if(map[i][j]>='a'&&map[i][j]<='e')  key[map[i][j]-'a'] ++ ;
            }
        }
        if(bfs())   printf("YES\n") ;
        else        printf("NO\n") ;
    }
    return 0 ;} 
原文地址:https://www.cnblogs.com/xiaolongchase/p/2414155.html