HDU 1429 bfs 状态压缩

原文链接: HDU 1429 bfs 状态压缩

上一篇: HDU 4771 Stealing Harry Potter's Precious

下一篇: HDU 1427 dfs 速算24点

题意:迷宫中,一个起点,一个终点,迷宫中有墙,有门,门的钥匙也在迷宫中某处,只有拿到钥匙才能打开门,问能不能再T步(不含)之内逃出迷宫。

题解:在朴素BFS上增加了钥匙的状态,只有有钥匙才能打开门,总共有不超过10吧钥匙,所以用一个int的整数的二进制即可存储钥匙的状态。碰到门先判断状态,碰到钥匙更新状态

字符串后面有\n,最大长度是21

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <queue>

#define LL long long
int const MAX = 1e6 + 1;
int const INF = 1 << 30;
double const EPS = 0.00000001;
using namespace std;

char g[21][21];
int n, m, T;
bool vis[20][20][1 << 10];
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};

struct Node {
    int x, y, state, step;
};
Node st, t;

void setVis(Node &nd){
    vis[nd.x][nd.y][nd.state] = 1;
}

int bfs(){
    memset(vis, 0, sizeof(vis));
    queue<Node> q;
    q.push(st);
    setVis(st);
    while (!q.empty()){
        Node nd = q.front();
        q.pop();

        for (int i = 0; i < 4; i++){
            t.x = nd.x + dir[i][0], t.y = nd.y + dir[i][1];
            t.step = nd.step + 1, t.state = nd.state;

            //只将满足条件的加入队列
            if (t.x < 0 || t.y < 0 || t.x >= n || t.y >= m ||
                g[t.x][t.y] == '*' || t.step >= T)
                continue;

            char c = g[t.x][t.y];
            if (c == '^'){
                return t.step;
            }
            //如果是门且没有对应的钥匙
            if (c >= 'A' && c <= 'J' && !(t.state & (1 << (c - 'A'))))
                continue;
            //如果是钥匙,更新状态
            if (c >= 'a' && c <= 'j')
                t.state |= (1 << (c - 'a'));
            if (!vis[t.x][t.y][t.state]){
                q.push(t);
                setVis(t);
            }
        }
    }
    return -1;
}
int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);

    while (scanf("%d%d%d", &n, &m, &T) == 3){

        for (int i = 0; i < n; i++){
            scanf("%s", g[i]);
            for (int j = 0; j < m; j++)
                if (g[i][j] == '@')
                    st.x = i, st.y = j, st.step = 0, st.state = 0;
        }

        printf("%d\n", bfs());
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值