#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1e9+7;
const int N = 505;
const short dx[]={1,0,-1,0};
const short dy[]={0,1,0,-1};

int n,m,xa,xb,ya,yb;
int sum[N][N],cana[N][N];
bool vis[N][N];
string s[N];

bool ok(int x,int y){
    if(x<1||y<1||x>n||y>n||s[x][y]=='X')return false;
    return true;
}

int getsum(int x1,int y1,int x2,int y2){
    return sum[x2][y2]-sum[x2][y1-1]-sum[x1-1][y2]+sum[x1-1][y1-1];
}

bool solve(int k){
    if(m==1){
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                if(!cana[i][j])continue;
                int ss=getsum(max(1,i-k-1),max(1,j-k-1),min(n,i+k+1),min(n,j+k+1));
                if(i-k-1>=1&&j-k-1>=1)ss-=getsum(i-k-1,j-k-1,i-k-1,j-k-1);
                if(i-k-1>=1&&j+k+1<=n)ss-=getsum(i-k-1,j+k+1,i-k-1,j+k+1);
                if(i+k+1<=n&&j-k-1>=1)ss-=getsum(i+k+1,j-k-1,i+k+1,j-k-1);
                if(i+k+1<=n&&j+k+1<=n)ss-=getsum(i+k+1,j+k+1,i+k+1,j+k+1);

                if(ss>0)return true;
            }
        }
        return false;

    }
}

int main(){
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    cin>>n>>m;

    for(int i=1;i<=n;i++){
        cin>>s[i];
        s[i]="#"+s[i];
        for(int j=1;j<=n;j++){
            if(s[i][j]=='A'){
                xa=i;
                ya=j;
            }else if(s[i][j]=='B'){
                xb=i;
                yb=j;
            }
        }
    }

    queue<pair<int,int> >q;
    q.push({xb,yb});

    while(!q.empty()){
        pair<int,int> e=q.front();
        q.pop();
        sum[e.first][e.second]=1;
        for(int i=0;i<4;i++){
            int newx=e.first+dx[i];
            int newy=e.second+dy[i];

            if(ok(newx,newy)&&!sum[newx][newy])q.push({newx,newy});
        }
    }

    if(sum[xa][ya]){
        cout<<-1;
        return 0;
    }

    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            sum[i][j]=sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+sum[i][j];
        }
    }

    q.push({xa,ya});
    while(!q.empty()){
        pair<int,int> e=q.front();
        q.pop();
        cana[e.first][e.second]=1;
        for(int i=0;i<4;i++){
            int newx=e.first+dx[i];
            int newy=e.second+dy[i];

            if(ok(newx,newy)&&!cana[newx][newy])q.push({newx,newy});
        }
    }




    int lo=1;
    int hi=n;
    int ans=n;
    while(lo<=hi){
        int mid=(lo+hi)>>1;
        if(solve(mid)){
            hi=mid-1;
            ans=mid;
        }else{
            lo=mid+1;
        }
    }

    cout<<ans;
    return 0;
}