每组测试数据之间有一个空行。
4 5 17 @A.B. a*.*. *..*^ c..b* 4 5 16 @A.B. a*.*. *..*^ c..b*
16 -1
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
const int INF = 1<<10;
const int N = 22;
const int Size = 999999;
using namespace std;
char b[N][N] ;
int vis[N][N][INF];
struct node
{
int x,y,z,ans ;
}q[Size];
int n,m,T;
int mv[4][2] = {{1,0},{0,-1},{-1,0},{0,1}};
void BFS(int x ,int y)
{
int s = 0 , e = 0 ;
node f , t ;
t.x = x ;
t.y = y ;
t.ans = 0 ;
t.z = 0 ;
q[e++] = t ;
vis[t.x][t.y][t.z] = 1;
while(s < e)
{
t = q[s++] ;
if(b[t.x][t.y]=='^' && t.ans < T)
{
printf("%d\n", t.ans);
return ;
}
for(int i = 0;i < 4;i++)
{
f.x = t.x + mv[i][0];
f.y = t.y + mv[i][1];
f.z = t.z;
if(f.x >= 0 && f.x < n && f.y >= 0 && f.y < m && vis[f.x][f.y][f.z]==0)
{
if(b[f.x][f.y]=='@' || b[f.x][f.y]=='.' || b[f.x][f.y]=='^')
{
f.ans = t.ans + 1;
q[e++] = f ;
vis[f.x][f.y][f.z] = 1 ;
}
else if('a' <= b[f.x][f.y] && b[f.x][f.y] <='j' )
{
int sum = 0,kk,xx;
f.ans = t.ans + 1;
xx = f.z;
kk = b[f.x][f.y] - 'a' + 1;
for(int ll = 0;ll<kk;ll++)
{
sum = xx % 2;
xx /= 2;
}
if(sum==0)
f.z += pow(2,(b[f.x][f.y]-'a'));
vis[f.x][f.y][f.z] = 1 ;
q[e++] = f ;
}
else if('A' <= b[f.x][f.y] && b[f.x][f.y] <='J' )
{
int sum = 0,kk,xx;
f.ans = t.ans + 1;
xx = f.z;
kk = b[f.x][f.y] - 'A' + 1;
for(int ll = 0;ll<kk;ll++)
{
sum = xx % 2;
xx /= 2;
}
if(sum==1)
{
f.ans = t.ans + 1;
q[e++] = f ;
vis[f.x][f.y][f.z] = 1 ;
}
}
}
}
}
printf("-1\n");
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&T))
{
int x,y;
memset(vis,0,sizeof(vis));
for(int i = 0 ; i < n ; i++)
{
scanf("%s%*c", b[i]);
}
for(int i = 0;i<n;i++)
{
for(int j = 0;j < m;j++)
{
if(b[i][j]=='@')
{
x = i;
y = j;
break;
}
}
}
BFS(x,y);
}
return 0;
}
原文:http://blog.csdn.net/wjw0130/article/details/29803579