4 5 17 @A.B. a*.*. *..*^ c..b* 4 5 16 @A.B. a*.*. *..*^ c..b*
16 -1
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define maxn 25
using namespace std;
int vis[maxn][maxn][1 << 11];
char map[maxn][maxn];
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
struct node{
    int x, y ,step, key;
};
int n, m, t, sx, sy;
bool check(node a){
    if(a.x >= 0 && a.x < n && a.y >= 0 && a.y < m && map[a.x][a.y] != '*')
        return true;
    else
        return false;
}
int bfs(){
    node now, next;
    queue<node >q;
    now.x = sx;
    now.y = sy;
    now.step = 0;
    now.key = 0;
    vis[now.x][now.y][now.key] = true;
    q.push(now);
    while(!q.empty()){
        now = q.front();
        q.pop();
        if(map[now.x][now.y] == '^' && now.step < t){
            return now.step;
        }
        if(now.step > t) continue;
        for(int i = 0; i < 4; ++i){
            next.x = now.x + dir[i][0];
            next.y = now.y + dir[i][1];
            next.step = now.step + 1;
            if(check(next)){
                if(map[next.x][next.y] >= 'a' && map[next.x][next.y] <= 'z'){//钥匙
                    next.key = now.key | (1 << (map[next.x][next.y] - 'a'));//获得这个钥匙
                    if(!vis[next.x][next.y][next.key]){
                        vis[next.x][next.y][next.key] = 1;
                        q.push(next);
                    }
                }
                else if(map[next.x][next.y] >= 'A' && map[next.x][next.y] <= 'Z'){//门
                    next.key = now.key;
                    if(next.key & (1 << (map[next.x][next.y] - 'A'))){//拥有这个门的钥匙
                        if(!vis[next.x][next.y][next.key]){
                            vis[next.x][next.y][next.key] = 1;
                            q.push(next);
                        }
                    }
                }
                else {//路
                    next.key = now.key;
                    if(!vis[next.x][next.y][next.key]){
                        vis[next.x][next.y][next.key] = 1;
                        q.push(next);
                    }
                }
            }
        }
    }
    return -1;
}
int main (){
    while(scanf("%d%d%d", &n, &m, &t) != EOF){
        memset(vis, 0, sizeof(vis));
        for(int i = 0; i < n; ++i){
            scanf("%s", map[i]);
            for(int j = 0; j < m; ++j)
            if(map[i][j] == '@')
                sx = i, sy = j;
        }
        int ans;
        ans = bfs();
        printf("%d\n", ans);
    }
    return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
HDU 1429--胜利大逃亡(续)【BFS && 状态压缩】
原文:http://blog.csdn.net/hpuhjh/article/details/47620413