HDU 4771 BFS+状态压缩

这题意思就是求出从起点到所给出来的点的所有点的最少路径数

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N=105;
int n,m,k;
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
char s[N][N];
int p[N][N];
bool hash[N][N][N];
int num;
struct node {
    int x,y,step,key;
};


int bfs(int x,int y) {
    int i;
    queue<node>q;
    node cur,next;
    cur.x=x;
    cur.y=y;
    cur.step=0;
    cur.key=0;
    hash[cur.x][cur.y][cur.key]=1;
    q.push(cur);
    while(!q.empty()) {
        cur=q.front();
        q.pop();
        if(cur.key==num)return cur.step;
        for(i=0; i<4; i++) {
            next.x=cur.x+dir[i][0];
            next.y=cur.y+dir[i][1];
            if(next.x<0||next.x>=n||next.y<0||next.y>=m||s[next.x][next.y]=='#')continue;
            next.step=cur.step+1;
            next.key=cur.key;
            if(p[next.x][next.y])next.key=(next.key|(1<<(p[next.x][next.y]-1)));
            if(!hash[next.x][next.y][next.key]) {
                hash[next.x][next.y][next.key]=1;
                q.push(next);
            }
        }


    }


    return -1;
}
int main() {
    int i ,j,x,y,flag1,flag2,flag3,r;
    while(scanf("%d%d",&n,&m),n+m) {
        flag3=0;
        num=1;
        memset(p,0,sizeof(p));
        for(i=0; i<n; i++)
            scanf("%s",&s[i]);
        scanf("%d",&k);
        for( i=1; i<=k; i++) {
            scanf("%d%d",&x,&y);
            p[x-1][y-1]=i;
        }
        for(i=0; i<n; i++) {
            for(j=0; j<m; j++) {
                if(s[i][j]=='@') {
                    flag1=i;
                    flag2=j;
                    flag3=1;
                    break;
                }
            }
            if(flag3)break;
        }
        for(i=0,r=1; i<k-1; i++) {
            r=r*2;
            num+=r;
        }
        int ans;
        memset(hash,0,sizeof(hash));
        ans=bfs(flag1,flag2);
        printf("%d\n",ans);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值