#include<stdio.h>
#include<string.h>
struct point
{
int x,y;
};
struct point gate[26][2],que[2505];
char box[55][55];
int vis[55][55],cost[55][55];
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
int n,m;
bool is_not(int x,int y)
{
if(x<0 || y <0 || x >=n || y >=m || vis[x][y] || box[x][y]=='#')
return true;
else return false;
}
int bfs(int lx,int ly)
{
int rear=0,fron=0,i;
que[rear].x=lx;
que[rear].y=ly;
rear++;
while(fron<rear)
{
for(i=0;i<4;i++)
{
int nx=que[fron].x+dx[i];
int ny=que[fron].y+dy[i];
if(is_not(nx,ny)) continue;
vis[nx][ny]=1;
int tmpx=nx,tmpy=ny;
if(box[nx][ny]>='a' && box[nx][ny]<='z')//遇到传送阵的情况,改变下一层xy的值
{
if(gate[box[nx][ny]-'a'][0].x==nx && gate[box[nx][ny]-'a'][0].y==ny)
{
tmpx=gate[box[nx][ny]-'a'][1].x;
tmpy=gate[box[nx][ny]-'a'][1].y;
}
else{
tmpx=gate[box[nx][ny]-'a'][0].x;
tmpy=gate[box[nx][ny]-'a'][0].y;
}
}
nx=tmpx;
ny=tmpy;
cost[nx][ny]=cost[que[fron].x][que[fron].y]+1;
que[rear].x=nx;
que[rear].y=ny;
rear++;
if(box[nx][ny]=='Q') return cost[nx][ny];
}
fron++;
}
return 0;
}
int main()
{ int T;
scanf("%d",&T);
while(T--)
{
int i,j,L_x,L_y;
scanf("%d%d",&n,&m);
getchar();
memset(cost,0,sizeof(cost));
memset(vis,0,sizeof(vis));
memset(gate,-1,sizeof(gate));
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{ char ch;
scanf("%c",&ch);
box[i][j]=ch;
if(ch=='L')
{
box[i][j]='#';
L_x=i;
L_y=j;
vis[i][j]=1;
}
else if(ch>='a'&&ch<='z')
{
if(gate[ch-'a'][0].x==-1)
{
gate[ch-'a'][0].x=i;
gate[ch-'a'][0].y=j;
}
else
{
gate[ch-'a'][1].x=i;
gate[ch-'a'][1].y=j;
}
}
}
getchar();
}
int ans=bfs(L_x,L_y);
if(ans==0) printf("-1\n");
else printf("%d\n",ans);
}
return 0;
}
CDOJ 解救小Q
最新推荐文章于 2018-07-30 13:57:46 发布