#include <vector>
#include <iostream>
#include <queue>
#include <utility>
using namespace std;

int main(){

    int n, m, nsqrd;
    cin >> n >> m;

    nsqrd = n * n;

    vector<int> vi(nsqrd, -1);
    vector<vector<int> > g(nsqrd, vi);

    char c;
    int A, B;

    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++){
            cin >> c;

            if(c == '.'){
                if(j < n - 1)
                    g[i * n + j][i * n + j + 1] = g[i * n + j + 1][i * n + j] = 0;
                if(j > 0)
                    g[i * n + j][i * n + j - 1] = g[i * n + j - 1][i * n + j] = 0;
                if(i < n - 1)
                    g[i * n + j][i * n + j + n] = g[i * n + j + n][i * n + j] = 0;
                if(i > 0)
                    g[i * n + j][i * n + j - n] = g[i * n + j - n][i * n + j] = 0;
            }else if(c == 'X'){
                    if(j < n - 1)
                        g[i * n + j][i * n + j + 1] = g[i * n + j + 1][i * n + j] = 1;
                    if(j > 0)
                        g[i * n + j][i * n + j - 1] = g[i * n + j - 1][i * n + j] = 1;
                    if(i < n - 1)
                        g[i * n + j][i * n + j + n] = g[i * n + j + n][i * n + j] = 1;
                    if(i > 0)
                        g[i * n + j][i * n + j - n] = g[i * n + j - n][i * n + j] = 1;
            }else if(c == 'A')
                    A = i * n + j;
            else if(c == 'B')
                    B = i * n + j;

        }

    vector<bool> bio(nsqrd, false);

    queue<pair<int, int> > q;
    q.push(make_pair(A, 0));
    bio[A] = true;

    int cvor, d, minDist = 1000000;

    while(!q.empty()){
        cvor = q.front().first;
        d = q.front().second;
        q.pop();

        if(cvor == B && d < minDist)
            minDist = d;

        for(int i = 0; i < nsqrd; i++)
            if(g[cvor][i] != -1 && !bio[i]){
                q.push(make_pair(i, d + g[cvor][i]));
                bio[i] = true;
            }

    }

    if(minDist == 0)
        cout << -1 << endl;
    else cout << minDist << endl;

    return 0;
}