【hdu】1885 Key Task【状压+bfs】

本文介绍了一种解决含钥匙和门的迷宫问题的算法,使用BFS遍历方法,并记录钥匙状态避免重复路径,最终找到最短逃生路径。

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

题意:

走迷宫,问走出迷宫最少需要多少步,其中要想通过一个含有门的格子,需要先经过含有该门对应的钥匙的地方

题解:

之前做过类似的一道题目,十分相似,不过这次做的时候还是出了点小问题,我vis只开了两位,发现就无法走回头路了,后来多加了一位存钥匙的状态,这样就可以判断重复情况了,以后记住了

#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=105;
int n,m,sx,sy,ex,ey;
char g[N][N];
bool vis[N][N][16];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
    int x,y,key,step;
};
int judged(char ch)
{
    if(ch=='B')return 1<<0;
    if(ch=='Y')return 1<<1;
    if(ch=='R')return 1<<2;
    if(ch=='G')return 1<<3;
}
int judgek(char ch)
{
    if(ch=='b')return 1<<0;
    if(ch=='y')return 1<<1;
    if(ch=='r')return 1<<2;
    if(ch=='g')return 1<<3;
    return 0;
}
void solve()
{
    memset(vis,0,sizeof(vis));
    queue<node>q;
    node u,v;
    u.x=sx;u.y=sy;u.key=0;u.step=0;vis[u.x][u.y][u.key]=1;
    q.push(u);
    while(!q.empty()){
        u=q.front();q.pop();
        if(g[u.x][u.y]=='X'){printf("Escape possible in %d steps.\n",u.step);return;}
        for(int i=0;i<4;i++){
            v.x=u.x+dir[i][0];v.y=u.y+dir[i][1];v.step=u.step+1;v.key=u.key|judgek(g[v.x][v.y]);
            if(v.x<1||v.x>n)continue;
            if(v.y<1||v.y>m)continue;
            if(g[v.x][v.y]=='#')continue;
            if(vis[v.x][v.y][v.key])continue;
            if(g[v.x][v.y]=='B'||g[v.x][v.y]=='Y'||g[v.x][v.y]=='R'||g[v.x][v.y]=='G'){
                if(!(u.key&judged(g[v.x][v.y]))) continue;
            }
            vis[v.x][v.y][v.key]=1;
            q.push(v);
        }
    }
    printf("The poor student is trapped!\n");
}
int main()
{//freopen("C:\\Users\\Administrator\\Desktop\\input.txt","r",stdin);
    //B Y R G door
    //# wall
    //. free square
    //* my position
    //b y r g key
    //X exit
    while(scanf("%d%d",&n,&m)&&n+m){
        for(int i=1;i<=n;i++)scanf("%s",g[i]+1);
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                if(g[i][j]=='*'){sx=i;sy=j;g[sx][sy]='.';break;break;}
            }
        }
        solve();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值