#include <bits/stdc++.h>

using namespace std;

char niz[505][505];
int dostizna[505][505];
int niz2[505][505];
bool pronasao = false;
int b1,b2;

void pronadji(int a, int b, n)
{
    if(pronasao) return;
    if(dostizna[a][b]!=-1) return return;
    if(a==0 || b==0 || a>n || b>n)
    {
        dostizna[a][b]=0;
        return;
    }
    if((a+1==b1 && b=b2) || (a-1==b1 && b=b2) || (a==b1 && b+1=b2) || (a+1==b1 && b-1=b2))
    {
        pronasao = true;
        return;
    }
    if(niz[a+1][b]=='.')
    {
        dostizna[a+1][b]=1;
        pronadji(a+1, b, n);
    }
    else dostizna[a+1][b]=0;
    if(niz[a-1][b]=='.')
    {
        dostizna[a-1][b]=1;
        pronadji(a-1, b, n);
    }
    else dostizna[a-1][b]=0;
    if(niz[a][b+1]=='.')
    {
        dostizna[a][b+1]=1;
        pronadji(a, b+1, n);
    }
    else dostizna[a][b+1]=0;
    if(niz[a+1][b]=='.')
    {
        dostizna[a][b-1]=1;
        pronadji(a, b-1, n);
    }
    else dostizna[a-1][b-1]=0;
}

int main()
{
    int n, m, a1, a2;
    cin >> n >> m;
    for(int i = 1; i<=n; i++)
    {
        for(int i = 1; i<=n; i++)
        {
            cin >> a[i][j];
            if(niz[i][j]=='A')
            {
                a1=i; a2=j;
            }
            else if(a[i][j]=='B')
            {
                b1=i; b2=j;
            }
        }
    }
    for(int i = 1; i<=n; i++)
    {
        for(int i = 1; i<=n; i++)
        {
            dostizna[i][j] = -1;
        }
    }
    dostizna[a1][a2] = 1;
    pronadji(a1, a2, n);
    if(pronasao)
    {
        cout << -1;
        return 0;
    }
    for(int i = 1; i<=n; i++)
    {
        for(int i = 1; i<=n; i++)
        {
            if(dostizna[i][j] == -1)
                dostizna[i][j]=0;
        }
    }
    return 0;
}