#include <bits/stdc++.h>
using namespace std;
vector <string> a;
vector <string> cpy;
vector <string> CanGo;
vector <bool> Bio[500];
bool OK=0;

void _DFS(int x,int y,int First=false){
    if(x<0||y<0||x>=a.size()||y>=a.size())return;
if(Bio[x][y])return;
//if(OK)return;
if(cpy[x][y]=='B'){Bio[x][y]=1;OK=1;return;}
if(cpy[x][y]!='.'&&cpy[x][y]!='A'&&cpy[x][y]!='U')return;
Bio[x][y]=1;
//if(First)cout <<"Damn "<<x<<" "<<y<<endl;
if(First)CanGo[x][y]='X';
_DFS(x+1,y,First);
_DFS(x-1,y,First);
_DFS(x,y+1,First);
_DFS(x,y-1,First);
}
void DFS(int x,int y,bool First=false){
for(int i=0;i<a.size();i++){
        Bio[i].clear();
Bio[i].resize(a.size(),0);

}
OK=0;
_DFS(x,y,First);
}

void Main1(int n){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

a.resize(n);
int x=0;
int y=0;
CanGo.resize(n);
for(int i=0;i<n;i++){
    cin >>a[i];
    for(int j=0;j<n;j++)if(a[i][j]=='A'){x=i;y=j;}
}
for(int i=0;i<n;i++)for(int j=0;j<n;j++)CanGo[i]+='O';

int l=0;
int r=n/2;
cpy=a;



while(l<r){
    int k=(l+r)/2;



    for(int i=0;i<n;i++){
            cpy=a;
             if(CanGo[i][0]!='X')continue;
        for(int xx=max(0,i-k);xx<min(i+k+1,n);xx++)
                for(int yy=max(0,i-k);yy<min(i+k+1,n);yy++){
                    if(cpy[xx][yy]=='X')cpy[xx][yy]='U';
                }

        for(int j=1;j<n;j++){
                if(CanGo[0][0]!='X')continue;
        for(int xx=max(0,i-k);xx<min(n,k+i+1);xx++){if(cpy[xx][max(0,j-k-1)]=='U')cpy[xx][max(0,j-k-1)]='X';}
        for(int xx=max(0,i-k);xx<min(n,k+i+1);xx++){if(cpy[xx][min(n-1,j+k)]=='X')cpy[xx][min(n-1,j+k)]='U';}
        OK=0;
        DFS(x,y);
        if(OK){
                cout <<"OK "<<k<<endl;
            r=k-1;

        }
        }


    }
        if(r!=k-1)l=k+1;

}
cout <<l<<endl;

}
int main(){
int n,m;
cin >>n>>m;
if(m==1){
    Main1(n);
}
}