#include <bits/stdc++.h>
using namespace std;
char a[505][505];
bool visited[505][505];
bool visited1[505][505];
int resenjekonacno = 501;
pair <int,int> l[3000];
int br = 1;
int max1 = 51;
void resenje(int n, int x1, int y1, int x2, int y2) {
    visited[x1][y1] = true;
    if (x1 > 1 && !visited[x1 - 1][y1]) {
        l[br].first = x1 - 1;
        l[br].second = y1;
        br++;
        resenje(n, x1 - 1, y1, x2, y2);
    }
    if (x1 < n - 1 && !visited[x1 + 1][y1]) {
        l[br].first = x1 + 1;
        l[br].second = y1;
        br++;
        resenje(n, x1 + 1, y1, x2, y2);
    }
    if (y1 > 1 && !visited[x1][y1 - 1]) {
        l[br].first = x1;
        l[br].second = y1 - 1;
        br++;
        resenje(n, x1, y1 - 1, x2, y2);
    }
    if (y1 < n - 1 && !visited[x1][y1 + 1]) {
        l[br].first = x1;
        l[br].second = y1 + 1;
        br++;
        resenje(n, x1, y1 + 1, x2, y2);
    }
}
void resenje1(int n, int x1, int y1, int x2, int y2) {
    visited1[x1][y1] = true;
    int max2 = max(abs(x2 - x1), abs(y2 - y1));
    max1 = min (max2, max1);
    if (x1 > 1 && !visited1[x1 - 1][y1])
        resenje(n, x1 - 1, y1, x2, y2);
    if (x1 < n - 1 && !visited1[x1 + 1][y1])
        resenje(n, x1 + 1, y1, x2, y2);
    if (y1 > 1 && !visited1[x1][y1 - 1])
        resenje(n, x1, y1 - 1, x2, y2);
    if (y1 < n - 1 && !visited1[x1][y1 + 1])
        resenje(n, x1, y1 + 1, x2, y2);
}
int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> a[i][j];
        }
    }
    int x1, y1, x2, y2;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
        if (a[i][j] == 'A') {
            x1 = i;
            y1 = j;
        }
        if (a[i][j] == 'B') {
            x2 = i;
            y2 = j;
        }
        if (a[i][j] == 'X') {
            visited[i][j] = true;
            visited1[i][j] = true;
        }
    }
    resenje(n, x1, y1, x2, y2);
    for (int i = 0; i < br; i++) {
        resenje1(n, x2, y2, l[i].first, l[i].second);
        resenjekonacno = min(resenjekonacno, max1);
    }
    cout << resenjekonacno;
    return 0;
}