#include <bits/stdc++.h>

using namespace std;

bool visited[505][505];
int n, m;
char mat[505][505], mat1[505][505];
vector<pair<int, int> > vec;
pair<int, int> apos;


bool bfs(int x, int y){
    if (x < 0 || y < 0 || x > n - 1 || y > n - 1)
        return false;
    if (visited[x][y])
    return false;
    visited[x][y] = true;
    if (mat1[x][y] == 'X')
        return false;
    if (mat1[x][y] == 'B')
        return true;
    if (bfs(x+1, y) || bfs(x-1, y) || bfs(x, y+1) || bfs(x, y-1))
        return true;
    return false;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin >> n >> m;
    for (int i = 0; i < n; ++i){
        for (int j = 0; j < n; ++j){
            cin >> mat[i][j];
            if (mat[i][j] == '.' || mat[i][j] == 'A'){
                vec.push_back(make_pair(i, j));
            }
            if (mat[i][j] == 'A')
                apos = make_pair(i, j);
        }
    }
    int maxf = 2147000000;
    for (int k = 0; k < n; ++k){
            for (int l = 0; l < n; ++l){
                  mat1[k][l] = mat[k][l];
                  visited[k][l] = false;
                }
            }
    if (bfs(apos.first, apos.second)){
        cout << 0;
        return 0;
    }
    for (int i = 0; i < vec.size(); ++i){
        for (int j = 1;; ++j){
            for (int k = 0; k < n; ++k){
            for (int l = 0; l < n; ++l){
                  mat1[k][l] = mat[k][l];
                  visited[k][l] = false;
                }
            }
            for (int k = vec[i].first - j; k <= vec[i].first + j; ++k){
                for (int l = vec[i].second - j; l <= vec[i].second + j; ++l){
                    if (!(k < 0  || l < 0 || k >= n || l >= n) && mat[k][l] != 'A' && mat[k][l] != 'B')
                        mat[k][l] = '.';
                }
            }
            if (bfs(apos.first, apos.second)){
                maxf = min(maxf, j);
                break;
            }
        }
    }
    cout << maxf;
    return 0;
}