Ignatius再次被魔王抓走了(搞不懂他咋这么讨魔王喜欢)……
这次魔王汲取了上次的教训,把Ignatius关在一个n*m的地牢里,并在地牢的某些地方安装了带锁的门,钥匙藏在地牢另外的某些地方。刚开始Ignatius被关在(sx,sy)的位置,离开地牢的门在(ex,ey)的位置。Ignatius每分钟只能从一个坐标走到相邻四个坐标中的其中一个。魔王每t分钟回地牢视察一次,若发现Ignatius不在原位置便把他拎回去。经过若干次的尝试,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
每组测试数据之间有一个空行。
. 代表路
* 代表墙
@ 代表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
<pre name="code" class="cpp">#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<ctype.h>
#include<math.h>
#include<queue>
using namespace std;
int n, m, count, sum, flag;
int T, sx, sy;
char str[110][110];
int used[21][21][1<<10];
struct node
{
int x, y, key, dis;
};
int mx[4]={ 0, 0, -1, 1 };
int my[4]={ -1, 1, 0, 0 };
void bfs()
{
int i;
node now, next;
queue<node>q;
while( !q.empty() )
q.pop();
now.x=sx;
now.y=sy;
now.dis=0;
now.key=0;
q.push( now );
while( !q.empty() )
{
now=q.front();
q.pop();
for( i=0;i<4;i++ )
{
next.x=now.x+mx[i];
next.y=now.y+my[i];
next.dis=now.dis+1;
next.key=now.key;
if( next.x<0||next.x>=n||next.y<0||next.y>=m||str[next.x][next.y]=='*' )
continue;
if( str[next.x][next.y]=='^'&&next.dis<T )
{
sum=next.dis ;
return ;
}
if( str[next.x][next.y]>='a'&&str[next.x][next.y]<='j'&&next.dis<T )
{
next.key=now.key|( 1<<( str[next.x][next.y]-'a' ) );
if( used[next.x][next.y][next.key]==0 )
{
q.push( next );
used[next.x][next.y][next.key]=1;}}
else if( str[next.x][next.y]>='A'&&str[next.x][next.y]<='J'&&next.dis<T )
{
if( next.key&( 1<<( str[next.x][next.y]-'A' ) )&&used[next.x][next.y][next.key]==0 )
{
q.push( next );used[next.x][next.y][next.key]=1;
}
}
else
{
if( used[next.x][next.y][next.key]==0 )
{
q.push( next );used[next.x][next.y][next.key]=1;
}
}
}
}
}
int main()
{
int i, j, k, t, cas=0;
while( scanf( "%d%d%d",&n, &m, &T )!=-1 )
{
for( i=0;i<n;i++ )
{
scanf( "%s",str[i] );
for( j=0;j<m;j++ )
{
if( str[i][j]=='@' )
sx=i,sy=j,str[i][j]=='.';
}
}
memset( used,0,sizeof( used ) );
sum=T;
bfs();
if( sum>=T )
printf( "-1\n" );
else
printf( "%d\n",sum );
}
return 0;
}