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
Hint
Source
QAsQ
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
int n,m;
char mm[303][303];
bool vis[303][303];
int step[4][2]={
{0,1},{0,-1},
{1,0},{-1,0}
};
struct node
{
int x,y,ans;
}t;
void bfs(int x, int y)
{
queue<node>q;
t.x = x;
t.y = y;
t.ans = 0;
q.push(t);
vis[t.x][t.y] = true;
while(!q.empty())
{
node cur = q.front();
q.pop();
if(mm[cur.x][cur.y] == 'O')
{
cout<<cur.ans<<endl;
return ;
}
//cout<<cur.x<<' '<<cur.y<<' '<<cur.ans<<endl;
for (int i = 0; i < 4; ++i)
{
t.x = cur.x + step[i][0];
t.y = cur.y + step[i][1];
if(t.x < 1||t.x > n ||t.y < 1|| t.y >m)
continue;
//cout<<"t.x t.y "<<t.x<<' '<<t.y<<endl;
if(!vis[t.x][t.y] && mm[t.x][t.y] != '#')
{
// cout<<t.x<<' '<<t.y<<endl;
t.ans = cur.ans+1;
vis[t.x][t.y] = true;
q.push(t);
}
}
}
cout<<-1<<endl;
}
int main(int argc, char const *argv[])
{
int T;
cin>>T;
while(T--)
{
memset(vis,false,sizeof(vis));
int x,y;
cin>>n>>m;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= m; ++j)
{
char c;
cin>>c;
mm[i][j] = c;
if(c == 'A')
{
x = i;
y = j;
}
}
}
//cout<<x<<y<<endl;
bfs(x,y);
}
return 0;
}