#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define si short int
#define vi vector<ll>
#define vii vector<vi>
#define vip vector<pair<ll,ll>>

ll xa,ya,xb,yb;
char put[505][505];

bool ima_put(ll n, ll x1, ll y1, ll x2, ll y2);
//bool posecen[505][505]={true};
//ll kon=0;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    ll n,m;
    cin>>n>>m;
    for(ll i=0;i<n;i++)
    {
        for(ll j=0;j<n;j++)
        {
            cin>>put[i][j];
            if(put[i][j]=='A') xa=i, ya=j;
            else if(put[i][j]=='B') xb=i, yb=j;
        }
    }
    if(ima_put(n, xa,ya,xb,yb)==true) cout<<"-1";
    return 0;
}


bool ima_put(ll n, ll x1, ll y1, ll x2, ll y2)
{
    if(put[x1+1][y1]=='B' || put[x1-1][y1]=='B' || put[x1][y1+1]=='B' || put[x1][y1-1]=='B') return true;
    if(put[x1+1][y1]=='.' && x1+1<n) if(ima_put(n, x1+1,y1,x2,y2)==true) return true;
    if(put[x1][y1+1]=='.' && y1+1<n) if(ima_put(n,x1,y1+1,x2,y2)==true) return true;
    if(put[x1-1][y1]=='.' && x1>0) if(ima_put(n,x1-1,y1,x2,y2)==true) return true;
    if(put[x1][y1-1]=='.' && y1>0) if(ima_put(n,x1,y1-1,x2,y2)==true) return true;
    return false;
}