#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#define ull unsigned long long

using namespace std;

vector< pair<int,int> >Danilo,Drug;

ull N,M;
ull sx,sy,kx,ky;
char S[1000][1000];
bool Da[1000][1000],
     Dr[1000][1000];

bool ns=false,nk=false;

ull minD=1000000;

char accessA(int x,int y){
 if(x>=0 && x<N && y>=0 && y<N) return S[x][y];
 else return 'X';
}
char accessB(int x,int y){
 if(x>=0 && x<N && y>=0 && y<N) return S[x][y];
 else return 'X';
}

void pA(int x,int y){
 Da[x][y]=true;
 Danilo.push_back(make_pair(x,y));
 if(accessA(x-1,y)=='.')
    if(!Da[x-1][y]) pA(x-1,y);

 if(accessA(x,y-1)=='.')
    if(!Da[x][y-1]) pA(x,y-1);

 if(accessA(x+1,y)=='.')
    if(!Da[x+1][y]) pA(x+1,y);

 if(accessA(x,y+1)=='.')
    if(!Da[x][y+1]) pA(x,y+1);
}

void pB(int x,int y){
 Dr[x][y]=true;
 Drug.push_back(make_pair(x,y));

 if(accessB(x-1,y)=='.')
    if(!Dr[x-1][y]) pB(x-1,y);

 if(accessB(x,y-1)=='.')
    if(!Dr[x][y-1]) pB(x,y-1);

 if(accessB(x+1,y)=='.')
    if(!Dr[x+1][y]) pB(x+1,y);

 if(accessB(x,y+1)=='.')
    if(!Dr[x][y+1]) pB(x,y+1);
}

int main()
{
    scanf("%llu%llu",&N,&M);
    getchar();
    for(int i=0;i<N;i++){
     gets(S[i]);
     if(!ns || !nk)
          for(int j=0;j<N;j++){
              if(S[i][j]=='A'){
                sx=i;
                sy=j;
              }
              if(S[i][j]=='B'){
                kx=i;
                ky=j;
              }
          }
    }

    pA(sx,sy);
    pB(kx,ky);

    for(int i=0;i<Danilo.size();i++)
        for(int j=0;j<Drug.size();j++){
         ull x1,x2,y1,y2;
         x1=Danilo[i].first;
         y1=Danilo[i].second;
         x2=Drug[j].first;
         y2=Drug[j].second;

         ull Distance;
         Distance=max(abs(x1-x2),abs(y1-y2));
         if(Distance==0 || Distance==1){
          printf("0");
          return 0;
         }
         //printf("(%llu,%llu) | (%llu,%llu) => %llu\n",x1,y1,x2,y2,Distance);

         if(Distance<minD) minD=Distance;

        }

    printf("%lld",minD/M);

    return 0;
}
/*
6 1
A.XX..
..XX..
XXXX..
..XX..
..XX..
..XX.B

7 2
AXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXB
*/