#include <bits/stdc++.h>
using namespace std;
char a[505][505];
string s;
int visited[505][505];
queue <pair <int, int> > red;
vector <pair <int, int> > k1, k2;
void bfs(vector <pair<int, int> > &v, int x1, int y1, int n)
{
    int i, x, y;
    for(i = 0; i <= n + 1; i++)
    {
        visited[i][0] = 1;
        visited[0][i] = 1;
        visited[i][n + 1] = 1;
        visited[n + 1][i] = 1;
    }
    red.push(make_pair(y1, x1));
    visited[y1][x1] = 1;
    while(red.size() > 0)
    {
        y = red.front().first;
        x = red.front().second;
        v.push_back(make_pair(y, x));
        red.pop();
        if(visited[y][x + 1] == 0 && a[y][x + 1] != 'X')
        {
            visited[y][x + 1] = 1;
            red.push(make_pair(y, x + 1));
        }
        if(visited[y][x - 1] == 0 && a[y][x - 1] != 'X')
        {
            visited[y][x - 1] = 1;
            red.push(make_pair(y, x - 1));
        }
        if(visited[y + 1][x] == 0 && a[y + 1][x] != 'X')
        {
            visited[y + 1][x] = 1;
            red.push(make_pair(y + 1, x));
        }
        if(visited[y - 1][x] == 0 && a[y - 1][x] != 'X')
        {
            visited[y - 1][x] = 1;
            red.push(make_pair(y - 1, x));
        }
    }
}
int main()
{
    int n, i, j, k, xa, ya, xb, yb, mn, mx;
    cin >> n >> k;
    for(i = 1; i <= n; i++)
    {
        cin >> s;
        for(j = n; j > 0; j--)
        {
        a[i][j] = s[j - 1];
        if(a[i][j] == 'A'){xa = j; ya = i;}
        if(a[i][j] == 'B'){xb = j; yb = i;}
        }
    }
    bfs(k1, xa, ya, n);
    if(visited[yb][xb] == 1) {cout << 0; return 0;}
    bfs(k2, xb, yb, n);
    mn = max(abs(k1[0].first - k2[0].first), abs(k1[0].second - k2[0].second));
    for(i = 0; i < k1.size(); i++)
        for(j = 0; j < k2.size(); j++)
        {
            ya = k1[i].first - k2[i].first;
            xa = k1[i].second - k2[j].second;
            if(ya < 0) ya = -ya;
            if(xa < 0) xa = -xa;
            if(ya > xa) mx = ya;
            else mx = xa;
            if(mx < mn) mn = mx;
        }
    cout << mn - 1;
    return 0;
}