HDU 4771 Stealing Harry Potter's Precious(BFS)

就是一道简单的BFS,由于要拿到所有宝藏,那么我们可以状态压缩宝藏集合, 为了使得状态表示完整,就需要在状态数组d中多增加一维。比较常见的题型。

细节参见代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int INF = 1000000000;
const int maxn = 505;
int q,n,m,d[maxn][maxn][5],vis[maxn][maxn],x,y;
struct node {
    int x,y,haha;
    node(int x=0, int y=0, int haha=0):x(x),y(y),haha(haha) {}
    bool operator == (const node& rhs) const {
        return x == rhs.x && y == rhs.y;
    }
}S;
char s[maxn][maxn];
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
int bfs(node S) {
    queue<node> Q;
    memset(d,-1,sizeof(d));
    d[S.x][S.y][S.haha] = 0;
    Q.push(S);
    while(!Q.empty()) {
        node u = Q.front(); Q.pop();
        if(u.haha == ((1<<q)-1)) return d[u.x][u.y][u.haha];
        for(int i=0;i<4;i++) {
            node v = u;
            v.x += dx[i]; v.y += dy[i];
            if(v.x < 1 || v.x > n || v.y < 1 || v.y > m) continue;
            if(vis[v.x][v.y] != -1)
                v.haha |= (1<<vis[v.x][v.y]);
            if(d[v.x][v.y][v.haha] == -1 && s[v.x][v.y] != '#') {
                d[v.x][v.y][v.haha] = d[u.x][u.y][u.haha] + 1;
                Q.push(v);
            }
        }
    }
    return -1;
}
int main() {
    while(~scanf("%d%d",&n,&m)) {
        if(!n && !m) break;
        memset(vis,-1,sizeof(vis));
        for(int i=1;i<=n;i++) scanf("%s",s[i]+1);
        bool ok = false;
        for(int i=1;i<=n;i++) {
            for(int j=1;j<=m;j++) {
                if(s[i][j] == '@') { S = node(i,j,0); ok = true; break; }
            }
            if(ok) break;
        }
        scanf("%d",&q);
        for(int i=0;i<q;i++) {
            scanf("%d%d",&x,&y);
            vis[x][y] = i;
            if(x == S.x && y == S.y) 
                S.haha |= (1<<i);
        }
        printf("%d\n",bfs(S));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值