BFS+状态压缩 hdu-1429 胜利大逃亡(续)

本文介绍了一道经典的迷宫寻路问题,通过状态压缩和广度优先搜索(BFS)的方法来解决含有钥匙和门的复杂迷宫路径寻找问题。文章详细解释了如何使用状态压缩来记录获取钥匙的状态,并通过BFS算法找到从起点到终点的最短路径。

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

题目链接:

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

题目意思:
给一个矩阵,告诉起点和终点,有些位置是墙不能走,有些位置是门,要拿到对应钥匙才能走,有些位置是钥匙。每走一步花一分钟。

问从起点到终点能否在t分钟内走到,如果能输出最短的到达时间,如果不能则输出-1。

解题思路:

状态压缩+BFS

每一把钥匙对应一位,拿到了为1,没有拿到则为0.

直接BFS就行了。

代码:

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#define eps 1e-6
#define INF 0x1f1f1f1f
#define PI acos(-1.0)
#define ll __int64
#define lson l,m,(rt<<1)
#define rson m+1,r,(rt<<1)|1
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;

/*
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
*/

bool vis[1<<11][25][25];
char save[25][25];
int n,m,t,dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};

struct Point
{
   int x,y,ss;
   int r;
};

bool iscan(int x,int y)
{
   if(x<1||x>n||y<1||y>m||save[x][y]=='*')
      return false;
   return true;
}

Point s;

void bfs()
{
  memset(vis,false,sizeof(vis));
  queue<Point>myq;
  s.ss=0;
  s.r=0;
  myq.push(s);
  vis[0][s.x][s.y]=true; //一把钥匙都没拿到

  while(!myq.empty())
  {
     Point tmp=myq.front();
     myq.pop();

     int xx,yy;
     for(int i=0;i<4;i++)
     {
        xx=tmp.x+dir[i][0],yy=tmp.y+dir[i][1];
        if(!iscan(xx,yy))
          continue;
        if(save[xx][yy]=='^') //到达出口
        {
           if(tmp.ss+1<t)
             printf("%d\n",tmp.ss+1);
           else
             printf("-1\n");  //最近的都不行,后面的肯定不行
           return ;
        }

        int tt=tmp.r;
        if(save[xx][yy]<='j'&&save[xx][yy]>='a') //又拿到一把钥匙
        {
          int  ta=1<<(save[xx][yy]-'a'+1);
          tt=tt|ta;
        }
        else if(save[xx][yy]<='J'&&save[xx][yy]>='A')
        {
           if(!(tmp.r&(1<<(save[xx][yy]-'A'+1)))) //没有打开此门的钥匙
               continue;
        }
        if(vis[tt][xx][yy]) //该状态之前已经访问过
           continue;
        vis[tt][xx][yy]=true;
        Point pp;
        pp.x=xx,pp.y=yy,pp.r=tt,pp.ss=tmp.ss+1;
        myq.push(pp);
     }

  }
  printf("-1\n"); //不可能到达出口
  return ;

}

int main()
{
   while(~scanf("%d%d%d",&n,&m,&t))
   {
      for(int i=1;i<=n;i++)
      {
         scanf("%s",save[i]+1);
         for(int j=1;j<=m;j++)
         {
            if(save[i][j]=='@')
               s.x=i,s.y=j;
         }
      }
      bfs();
   }

   return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值