HDU 1429 胜利大逃亡(续) (状压bfs)

胜利大逃亡(续)

 HDU - 1429 

Ignatius再次被魔王抓走了(搞不懂他咋这么讨魔王喜欢)…… 

这次魔王汲取了上次的教训,把Ignatius关在一个n*m的地牢里,并在地牢的某些地方安装了带锁的门,钥匙藏在地牢另外的某些地方。刚开始Ignatius被关在(sx,sy)的位置,离开地牢的门在(ex,ey)的位置。Ignatius每分钟只能从一个坐标走到相邻四个坐标中的其中一个。魔王每t分钟回地牢视察一次,若发现Ignatius不在原位置便把他拎回去。经过若干次的尝试,Ignatius已画出整个地牢的地图。现在请你帮他计算能否再次成功逃亡。只要在魔王下次视察之前走到出口就算离开地牢,如果魔王回来的时候刚好走到出口或还未到出口都算逃亡失败。 

Input

每组测试数据的第一行有三个整数n,m,t(2<=n,m<=20,t>0)。接下来的n行m列为地牢的地图,其中包括: 

. 代表路 
* 代表墙 
@ 代表Ignatius的起始位置 
^ 代表地牢的出口 
A-J 代表带锁的门,对应的钥匙分别为a-j 
a-j 代表钥匙,对应的门分别为A-J 

每组测试数据之间有一个空行。 

Output

针对每组测试数据,如果可以成功逃亡,请输出需要多少分钟才能离开,如果不能则输出-1。 

Sample Input

4 5 17
@A.B.
a*.*.
*..*^
c..b*

4 5 16
@A.B.
a*.*.
*..*^
c..b*

Sample Output

16
-1
//#include<bits/stdc++.h>
//#include <unordered_map>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<set>
#include<climits>
#include<queue>
#include<cmath>
#include<stack>
#include<map>
using namespace std;
#define LL long long
#define MT(a,b) memset(a,b,sizeof(a))
const int INF  =  0x3f3f3f3f;
const int ONF  = -0x3f3f3f3f;
const int mod  =  998244353;
const int maxn =  5e4+5;
const int N    =  5e4+5;
const double PI  =  3.141592653589;
const double E   =  2.718281828459;

struct dd{
    int x,y,t,k; // k表示拥有钥匙的状态,t表示在(x,y)位置k状态下的最小步数
}st;

int run[4][2] = {1,0,-1,0,0,1,0,-1};
int vis[30][30][1<<10];//vis[x][y][k] k表示拥有钥匙的状态,vis表示在k状态下是否走过(x,y)位置
char mp[30][30];
int n , m , time;

bool check(int x, int y,int k){
    return x<0||x>=n||y<0||y>=m||vis[x][y][k]||mp[x][y]=='*';
}

int bfs()
{
    queue<dd>Q; Q.push(st);
    MT(vis,0);  vis[st.x][st.y][st.k] = 1;//压入起点,并标记
    while(!Q.empty())
    {
        dd now = Q.front(); Q.pop();
        for(int i=0;i<4;i++)
        {
            dd next = now;
            next.x += run[i][0];
            next.y += run[i][1];
            next.t ++;           //初始next

            char c = mp[next.x][next.y];

            if(check(next.x,next.y,next.k)) continue; //检查
            if(next.t>=time) return -1;               //到时间
            if(c=='^')       return next.t;           //到出口

            if(c>='a'&&c<='z')       next.k|=1<<(c-'a');                    //如果有钥匙,记录下来
            else if(c>='A'&&c<='Z')  if(!(next.k & (1<<c-'A') ))  continue; //如果遇到门,判断有不有钥匙

            Q.push(next); vis[next.x][next.y][next.k] = 1;                  //压入next并标记
        }
    }
    return -1;
}

int main()
{
    while(~scanf("%d%d%d",&n,&m,&time))
    {
        for(int i=0;i<n;i++)
        {
            scanf("%s",mp[i]);
            for(int j=0;j<m;j++) if(mp[i][j]=='@')  st={i,j,0,0};//记录起点
        }
        printf("%d\n",bfs());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Mannix_Y/article/details/81414867