#include<cstdio>
#include<iostream>
#include<cstring>
#include<deque>
#include<cmath>
using namespace std;
int n,m,cnta,cntb,razd,min_razd,razdx,razdy;
char c[505][505];
struct ss{
    int x,y;
} a,b,prvi,niza[250005],nizb[250005];
deque <ss> dq;
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
bool ubacen[505][505],gotovo,posecen[505][505];

void bfs(ss a, bool aba) {
    memset(ubacen,false,sizeof(ubacen));
    memset(posecen,false,sizeof(posecen));

    dq.push_back(a);
    posecen[a.x][a.y]=true;

    while (dq.size()) {
        prvi=dq.front();
        dq.pop_front();
//        printf("prvi.x:%d  prvi.y:%d\n", prvi.x, prvi.y);
        for (int i=0;i<=3;i++) {
            int idx=prvi.x+dx[i];
            int idy=prvi.y+dy[i];

            if (c[idx][idy]=='#' || posecen[idx][idy]==true) continue;

            if (c[idx][idy]=='X' && ubacen[prvi.x][prvi.y]==false) {
                if (aba) {
                    niza[++cnta].x=prvi.x;
                    niza[  cnta].y=prvi.y;
                }
                else {
                    nizb[++cntb].x=prvi.x;
                    nizb[  cntb].y=prvi.y;
                }
                ubacen[prvi.x][prvi.y]=true;
            }
            else if (c[idx][idy]=='B' && aba==true) {
//                printf("idx:%d  idy:%d\n", idx, idy);
                gotovo=true;
                return;
            }
            else if (c[idx][idy]!='X') {
                dq.push_back({idx,idy});
                posecen[idx][idy]=true;
            }
        }
    }
}

void Subtask1() {
    bfs(a,true);

    if (gotovo) {
        printf("0\n");
        return;
    }

    bfs(b,false);

//    printf("%d\n", cnta);
//    for (int i=1;i<=cnta;i++) printf("%d %d\n", niza[i].x, niza[i].y);
//    printf("%d\n", cntb);
//    for (int i=1;i<=cntb;i++) printf("%d %d\n", nizb[i].x, nizb[i].y);
//    return;

    min_razd=1e9;
    for (int i=1;i<=cnta;i++) {
        for (int j=1;j<=cntb;j++) {
            razdx=abs(niza[i].x - nizb[j].x);
            razdy=abs(niza[i].y - nizb[j].y);

            if (razdx==razdy) razd=razdx;
            else razd=max(razdx,razdy)-1;

            min_razd=min(min_razd,razd);
//            printf("i:%d  j:%d  nax:%d  nay:%d  nbx:%d  nby:%d  razd:%d  min_razd:%d\n", i, j, niza[i].x, niza[i].y, nizb[j].x, nizb[j].y, razd, min_razd);
        }
    }

    printf("%d\n", min_razd);
}

int main() {
    memset(c,'#',sizeof(c));

    scanf("%d %d", &n, &m);
    for (int i=1;i<=n;i++) {
        for (int j=1;j<=n;j++) {
            cin >> c[i][j];
            if (c[i][j]=='A') {a.x=i; a.y=j;}
            if (c[i][j]=='B') {b.x=i; b.y=j;}
        }
    }

    if (m==1) Subtask1();

    return 0;
}
/*
4 1
AX.B
X...
....
....
*/