Problem 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
Sample Output
6
-1
#include<bits/stdc++.h>
using namespace std;
const int maxx=1e6+10;
struct node
{
int x;
int y;
int s;
};
node que[maxx];
char e[1001][1001];
int book[1001][1001];
int nextt[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};
int main()
{
std::ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--)
{
int n,m;
cin>>n>>m;
int head,tail;
int i,j,k,startx,starty,p,q,tx,ty,flag=0;
memset(book,0,sizeof(book));
for(j=0; j<n; j++)
{
cin>>e[j];
}
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
if(e[i][j]=='A')
{
startx=i;
starty=j;
break;
}
if(e[i][j]=='O')
{
p=i;
q=j;
break;
}
}
}
// cout<<startx<<" $$$$"<<starty<<endl;
// cout<<p<<"%%%%%"<<q<<endl;
head=1,tail=1;
que[tail].x=startx;
que[tail].y=starty;
que[tail].s=0;
tail++;
book[startx][starty]=1;
while(head<tail)
{
for(k=0; k<=3; k++)
{
tx=que[head].x+nextt[k][0];
ty=que[head].y+nextt[k][1];
//cout<<tx<<"^^^^^"<<ty<<endl;
if(e[tx][ty]=='#'||tx<0||tx>=n||ty<0||ty>=m)
continue;
if((e[tx][ty]=='_'||e[tx][ty]=='O')&&book[tx][ty]==0)
{
book[tx][ty]=1;
que[tail].x=tx;
que[tail].y=ty;
que[tail].s=que[head].s+1;
tail++;
//cout<<"********"<<tx<<"&&&&&"<<ty<<endl;
}
if(tx==p&&ty==q)
{
flag=1;
break;
}
}
if(flag==1)
break;
head++;
//cout<<head<<" "<<tail<<endl;
}
if(flag)
cout<<que[tail-1].s<<endl;
else
cout<<"-1"<<endl;
}
return 0;
}