您的位置:首页 > 其它

HDU 1429--胜利大逃亡(续)【BFS && 状态压缩】

2017-05-21 20:32 513 查看

胜利大逃亡(续)

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 6656 Accepted Submission(s): 2315



[align=left]Problem Description[/align]
Ignatius再次被魔王抓走了(搞不懂他咋这么讨魔王喜欢)……

这次魔王汲取了上次的教训,把Ignatius关在一个n*m的地牢里,并在地牢的某些地方安装了带锁的门。钥匙藏在地牢另外的某些地方。刚開始Ignatius被关在(sx,sy)的位置,离开地牢的门在(ex,ey)的位置。Ignatius每分钟仅仅能从一个坐标走到相邻四个坐标中的当中一个。

魔王每t分钟回地牢视察一次。若发现Ignatius不在原位置便把他拎回去。经过若干次的尝试,Ignatius已画出整个地牢的地图。如今请你帮他计算是否能再次成功逃亡。仅仅要在魔王下次视察之前走到出口就算离开地牢,假设魔王回来的时候刚好走到出口或还未到出口都算逃亡失败。

[align=left]Input[/align]
每组測试数据的第一行有三个整数n,m,t(2<=n,m<=20,t>0)。接下来的n行m列为地牢的地图。当中包含:

. 代表路

* 代表墙

@ 代表Ignatius的起始位置

^ 代表地牢的出口

A-J 代表带锁的门,相应的钥匙分别为a-j

a-j 代表钥匙,相应的门分别为A-J

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

[align=left]Output[/align]
针对每组測试数据。假设能够成功逃亡。请输出须要多少分钟才干离开,假设不能则输出-1。

[align=left]Sample Input[/align]

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

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


[align=left]Sample Output[/align]

16
-1


#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define maxn 25
using namespace std;

int vis[maxn][maxn][1 << 11];
char map[maxn][maxn];
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};

struct node{
int x, y ,step, key;
};

int n, m, t, sx, sy;

bool check(node a){
if(a.x >= 0 && a.x < n && a.y >= 0 && a.y < m && map[a.x][a.y] != '*')
return true;
else
return false;
}

int bfs(){
node now, next;
queue<node >q;
now.x = sx;
now.y = sy;
now.step = 0;
now.key = 0;
vis[now.x][now.y][now.key] = true;
q.push(now);
while(!q.empty()){
now = q.front();
q.pop();
if(map[now.x][now.y] == '^' && now.step < t){
return now.step;
}
if(now.step > t) continue;
for(int i = 0; i < 4; ++i){
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
next.step = now.step + 1;
if(check(next)){
if(map[next.x][next.y] >= 'a' && map[next.x][next.y] <= 'z'){//钥匙
next.key = now.key | (1 << (map[next.x][next.y] - 'a'));//获得这个钥匙
if(!vis[next.x][next.y][next.key]){
vis[next.x][next.y][next.key] = 1;
q.push(next);
}
}
else if(map[next.x][next.y] >= 'A' && map[next.x][next.y] <= 'Z'){//门
next.key = now.key;
if(next.key & (1 << (map[next.x][next.y] - 'A'))){//拥有这个门的钥匙
if(!vis[next.x][next.y][next.key]){
vis[next.x][next.y][next.key] = 1;
q.push(next);
}
}
}
else {//路
next.key = now.key;
if(!vis[next.x][next.y][next.key]){
vis[next.x][next.y][next.key] = 1;
q.push(next);
}
}
}
}
}
return -1;
}

int main (){
while(scanf("%d%d%d", &n, &m, &t) != EOF){
memset(vis, 0, sizeof(vis));
for(int i = 0; i < n; ++i){
scanf("%s", map[i]);
for(int j = 0; j < m; ++j)
if(map[i][j] == '@')
sx = i, sy = j;
}
int ans;
ans = bfs();
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: