SuperCowHorse @ 2022-05-16 16:13:23
#include<bits/stdc++.h>
using namespace std;
struct node{
int x,y,z,fo;
}tmp;
queue<node>q;
char c;
int n,sx,sy,ex,ey,x,y,z,fo;
int a[105][105];
int dx[]={0,-1,0,1,0};
int dy[]={0,0,1,0,-1};
bool u[105][105];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
{
cin>>c;
if(c=='A') sx=i,sy=j;
if(c=='B') ex=i,ey=j;
if(c=='x') a[i][j]=1;
}
q.push((node){sx,sy,-1,5});
u[sx][sy]=1;
while(!q.empty())
{
tmp=q.front();q.pop();
x=tmp.x;y=tmp.y;z=tmp.z;fo=tmp.fo;
//printf("\n%d %d %d %d",x,y,z,fo);
for(int i=1;i<=4;++i)
{
int xx=x+dx[i];
int yy=y+dy[i];
if(!u[xx][yy]&&xx>=1&&yy>=1&&xx<=n&&yy<=n&&a[xx][yy]==0)
{
u[xx][yy]=1;
if(i!=fo)
q.push((node){xx,yy,z+1,i});
else
q.push((node){xx,yy,z,i});
}
if(x==ex&&y==ey)
{
printf("%d",tmp.z);
return 0;
}
}
}
printf("-1");
return 0;
}