hdu 4771 Stealing Harry Potter's Precious(BFS+状态压缩)

本文介绍了一种结合广度优先搜索(BFS)与状态压缩技术解决地图上收集所有宝藏最短步数问题的方法。通过使用状态压缩来记录已获取的宝藏,实现了高效的路径搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=4771

题目大意:

在一个地图上面有一些宝藏,现在从某一个点出发要拿到所有的宝藏,问最短所需要走的步数是多少。

思路:

BFS+状态压缩。

在原来的vis[][]基础上添加一个状态,vis[i][j][state]代表在(i,j)上面拿了多少个宝藏时候的最小步数。

题目范围比较小,宝藏最多有4个,所以我们可以将宝藏分别设为1,2,4,8(二进制)。这样我们就可以进行状态压缩了,任意的两个进行&运算就可以知道是否已经被拿过了,如果没拿过就用|运算添加。

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
int n,m,si,sj,sum;
char s[105][105];
int vis[105][105][35],dir[4][2]={0,1,0,-1,1,0,-1,0},maze[105][105];
struct node{
int x,y,step,state;
}p[105];
queue<node>qu;
int bfs()
{
    while(!qu.empty())
        qu.pop();
    node now,next;
    now.x=si;
    now.y=sj;
    now.step=0;
    now.state=maze[si][sj];
    qu.push(now);
    while(!qu.empty())
    {
        now=qu.front();
        qu.pop();
        if(now.state==sum)return now.step;
        for(int i=0;i<4;i++)
        {
            next=now;
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            next.step=now.step+1;
            if(maze[next.x][next.y]==-1)continue;
            if(next.x<=0||next.y<=0||next.x>n||next.y>m)continue;
            if(maze[next.x][next.y]>0&&(now.state&maze[next.x][next.y])==0)  //如果宝藏还没被拿过,就拿进去。
            next.state=now.state|maze[next.x][next.y];
            if(vis[next.x][next.y][next.state])continue;
            else {
                vis[next.x][next.y][next.state]=1;
                qu.push(next);
            }

        }
    }
    return -1;
}
int main()
{
    int i,j,k,q;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(n==0&&m==0)break;
        sum=0;
        memset(maze,0,sizeof(maze));
       for(i=1;i<=n;i++)
            for(j=1;j<=m;j++)
            {
                cin>>s[i][j];
             if(s[i][j]=='@'){
                    maze[i][j]=0;
                si=i;sj=j;
             }
             if(s[i][j]=='#'){
                maze[i][j]=-1;
             }
             if(s[i][j]=='.'){
                maze[i][j]=0;
             }
    }
    memset(vis,0,sizeof(vis));
    scanf("%d",&q);
    for(i=1;i<=q;i++)
    {
        int fx,fy;
        scanf("%d%d",&fx,&fy);
        maze[fx][fy]=1<<(i-1);
        sum+=maze[fx][fy];
    }
  //  printf("%d\n",sum);
   int ans= bfs();
   printf("%d\n",ans);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值