#include <bits/stdc++.h>

#define ll long long
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fi first
#define se second
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define pb push_back
#define mod 1000000007

using namespace std;

int n,m;
pair<int,int>a,b;
char c[510][510];
bool ch[510][510][2];

void check_zero(int i,int j){
    if (i==0 or i==n+1 or j==0 or j==m+1)return;
    if (ch[i][j][0] or c[i][j]=='X')return;
    ch[i][j][0]=true;
    if (make_pair(i,j)==b){
        cout<<-1<<"\n";
        exit(0);
    }
    check_zero(i+1,j);
    check_zero(i,j+1);
    check_zero(i-1,j);
    check_zero(i,j-1);
}

bool one(int i,int j,int k,int q,int f,int g){
    if (i<=0 or i>=n+1 or j<=0 or j>=m+1 or q==-1)return false;
    if (ch[i][j][q] or (c[i][j]=='X' and (abs(f-i)>k or abs(g-j)>k)))return false;
    ch[i][j][q]=true;
    if (make_pair(i,j)==b)return true;
    int t=max({one(i+1,j,k,q,f,g),
            one(i,j+1,k,q,f,g),
            one(i-1,j,k,q,f,g),
            one(i,j-1,k,q,f,g),
            one(i,j,k,q-1,i,j)});
    return t;
}

int main(){
    int ok;
    cin>>n>>ok;
    m=n;
    for (int i=1;i<=n;i++){
        for (int j=1;j<=m;j++){
            cin>>c[i][j];
            if (c[i][j]=='A'){
                c[i][j]='.';
                a={i,j};
            }
            if (c[i][j]=='B'){
                b={i,j};
            }
        }
    }
    check_zero(a.fi,a.se);
    int l=1,r=250,mid,ans=250;
    while(l<=r){
        memset(ch,0,sizeof(ch));
        mid=(l+r)/2;
        if (ok==1){
            if (one(a.fi,a.se,mid,1,1e9,1e9)){
                r=mid-1;
                ans=mid;
            }
            else l=mid+1;
        }
    }
    cout<<ans;
    return 0;
}
/*
za -1

7 9
X.X.XBXXX
XX.XX.XXX
XXX......
A.X....XX
X..XXX.XX
X.XXXX..X
.........

6 1
A.XX..
..XX..
XXXX..
..XX..
..XX..
..XX.B
*/