#include <bits/stdc++.h>
using namespace std;

#define pb push_back

int n, m;
int si, sj, ei, ej;
char mat[505][505], mat1[505][505];
vector<pair<int, int>> proso;
bool visited[505][505];
bool moze;

void dfs(int i, int j)
{
    visited[i][j] = true;
    proso.pb({i, j});

    if(i - 1 >= 0 && !visited[i - 1][j] && mat[i - 1][j] != 'X'){dfs(i - 1, j);}
    if(j + 1 < n && !visited[i][j + 1] && mat[i][j + 1] != 'X'){dfs(i, j + 1);}
    if(i + 1 < n && !visited[i + 1][j] && mat[i + 1][j] != 'X'){dfs(i + 1, j);}
    if(j - 1 >= 0 && !visited[i][j - 1] && mat[i][j - 1] != 'X'){dfs(i, j - 1);}
}

void mozeLi(int i, int j)
{
    visited[i][j] = true;
    if(mat[i][j] == 'B'){moze = true; return;}

    if(i - 1 >= 0 && !visited[i - 1][j] && mat[i - 1][j] != 'X'){mozeLi(i - 1, j);}
    if(j + 1 < n && !visited[i][j + 1] && mat[i][j + 1] != 'X'){mozeLi(i, j + 1);}
    if(i + 1 < n && !visited[i + 1][j] && mat[i + 1][j] != 'X'){mozeLi(i + 1, j);}
    if(j - 1 >= 0 && !visited[i][j - 1] && mat[i][j - 1] != 'X'){mozeLi(i, j - 1);}
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

    cin >> n >> m;

    for(int i = 0; i < n; ++i){
        for(int j = 0; j < n; ++j){
            cin >> mat[i][j];
            mat1[i][j] = mat[i][j];
            if(mat[i][j] == 'A'){
                si = i; sj = j;
            }
            if(mat[i][j] == 'B'){
                ei = i; ej = j;
            }
        }
    }

    int l = 0, r = 250;
    dfs(si, sj);
    while(l != r){
        int k = (l + r) / 2;

        for(auto gde : proso){
            for(int p = max(gde.first - k, 0); p <= min(gde.first + k, n - 1); ++p){
                for(int q = max(gde.second - k, 0); q <= min(gde.second + k, n - 1); ++q){
                    mat1[p][q] = mat[p][q];
                    mat[p][q] = (mat[p][q] != 'A' && mat[p][q] != 'B') ? '.' : mat[p][q];
                }
            }

            for(int i = 0; i < n; ++i){
                for(int j = 0; j < n; ++j){
                    visited[i][j] = false;
                }
            }

            moze = false;
            mozeLi(si, sj);

            for(int p = max(gde.first - k, 0); p <= min(gde.first + k, n - 1); ++p){
                for(int q = max(gde.second - k, 0); q <= min(gde.second + k, n - 1); ++q){
                    mat[p][q] = mat1[p][q];
                }
            }

            if(moze){break;}
        }

        if(moze){
            r = k;
        }
        else{
            l = k + 1;
        }
    }

    cout << l << "\n";

    return 0;
}