您的位置:首页 > 其它

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

2015-08-04 14:36 435 查看
Problem Description

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


有十个门,有十把钥匙,每把钥匙对应一个门,相同的门可以有多个。这样,我们就得按照状态来搜索,用10位二进制来表示每把钥匙的状态。和hdu 1885差不多。

#include <iostream>

#include <stdio.h>

#include <queue>

#include <string.h>

using namespace
std;

char map[25][25];

bool vis[25][25][1025];

int sx,sy,n,m,t;

int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};

struct node

{

int x;

int y;

int step;

int state;

node(int x=0,int y=0,int step=0,int
state=0)

{

this->x=x;

this->y=y;

this->step=step;

this->state=state;

}

};

bool check(int x,int y)

{

if(x<0 || x>=n || y<0 || y>=m ||map[x][y]=='*')

return
false;

return
true;

}

int bfs()

{

queue<node>q;

node temp,h;

q.push(node(sx,sy,0,0));

vis[sx][sy][0]=1;

while (!q.empty())

{

h=q.front();

q.pop();

for (int i=0; i<4; i++)

{

temp=h;

temp.x+=dir[i][0];

temp.y+=dir[i][1];

temp.step++;

if(temp.step>=t)

return
0;

if(check(temp.x, temp.y)&& !vis[temp.x][temp.y][temp.state])

{

if(map[temp.x][temp.y]=='^')

return temp.step;

if(map[temp.x][temp.y]=='.')

{

vis[temp.x][temp.y][temp.state]=1;

q.push(temp);

}

else
if(map[temp.x][temp.y]>='A' &&map[temp.x][temp.y]<='J'
)

{

int key=temp.state&(1<<(map[temp.x][temp.y]-'A'));//检查是否有钥匙

if(key)

{

vis[temp.x][temp.y][temp.state]=1;

q.push(temp);

}

}

else
if(map[temp.x][temp.y]>='a' &&map[temp.x][temp.y]<='j')

{

temp.state=temp.state|(1<<(map[temp.x][temp.y]-'a'));//获得钥匙,更新状态

if(!vis[temp.x][temp.y][temp.state])

{

vis[temp.x][temp.y][temp.state]=1;

q.push(temp);

}

}

}

}

}

return 0;

}

int main()

{

while (scanf("%d%d%d",&n,&m,&t)!=EOF)

{

getchar();

for (int i=0; i<n; i++)

{

for (int j=0; j<m; j++)

{

scanf("%c",&map[i][j]);

if(map[i][j]=='@')

{

sx=i;

sy=j;

map[i][j]='.';

}

}

getchar();

}

memset(vis,0,
sizeof(vis));

int ans=bfs();

if(ans)

printf("%d\n",ans);

else

puts("-1");

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: