Description
又到了汤圆星球一年一度的汤圆节了,但是大魔王却过来把汤圆公主抓走了Σ( ° △ °|||)︴
身为汤圆骑士的QAQ蒟蒻自然而然的肩负着拯救汤圆的使命
QAQ蒟蒻经历了千辛万苦(并没有)之后,来到了大魔王的城堡,根据情报,汤圆公主就被大魔王放在城堡内,然后QAQ蒟蒻发现自己是一个路
痴,所幸的是他拿到了大魔王的城堡的地图,而且在这上面标注了自己和汤圆公主的位置,那么问题来了,聪明的你能帮他计算出需要多少单位
的时间来赶到汤圆公主的位置吗?
Ps:QAQ蒟蒻每一次都可以移动到相邻的非墙的格子中,每次移动都要花费1个单位的时间
有公共边的格子定义为相邻
Input
一开始为一个整数T代表一共有T组数据
每组测试数据的第一行有两个整数n,m (2<=n,m<=300)
接下来的n行m列为大魔王的迷宫,其中
’#’为墙壁,‘_‘为地面
A代表QAQ蒟蒻,O代表汤圆公主:
Output
一组数据输出一个整数代表从QAQ蒟蒻到汤圆的位置的最短时间
如果QAQ蒟蒻不能到达汤圆的位置,输出-1
Sample
Input
2
3 3
__A
_##
__O
2 2
A#
#O
Output
6
-1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int x,y,step;
} w;
int a[300][300];
char mp[300][300];
int n,m,pre,post;
int x1,y1,x2,y2;
int mx[]= {0,0,-1,1},my[]= {1,-1,0,0};
int bfs(int n,int m)
{
struct node q[90000];
pre=post=0;
q[post].x=x1;
q[post].y=y1;
q[post].step=0;
post++;
a[x1][y1]=1;
while(pre<post)
{
w=q[pre++];
if(mp[w.x][w.y]=='O')
return w.step;
for(int i=0; i<4; i++)
{
int px=w.x+mx[i];
int py=w.y+my[i];
if(px>=0&&px<n&&py>=0&&py<m&&mp[px][py]!='#'&&!a[px][py])
{
q[post].x=px;
q[post].y=py;
q[post].step=w.step+1;
post++;
a[px][py]=1;
}
}
}
return -1;
}
int main()
{
int t,i,j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
memset(a,0,sizeof(a));
for(i=0; i<n; i++)
scanf("%s",mp[i]);
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
if(mp[i][j]=='A')
{
x1=i,y1=j;
break;
}
}
if(j!=m)break;
}
printf("%d\n",bfs(n,m));
}
return 0;
}