#include <iostream>

using namespace std;

char G[505][505];
int X[505];
int Y[505];
int k = 0;
bool K = false;
int mini = 505;

void mark(int x, int y, int N)
{
    if(x < 0 || y < 0 || x >= N || y >= N)
        return;
    if(G[x][y] == '.' || G[x][y] == 'B')
    {
        G[x][y] = '0';
        X[k] = x;
        Y[k] = y;
        k++;
        mark(x+1, y, N);
        mark(x, y+1, N);
        mark(x-1, y, N);
        mark(x, y-1, N);
    }
    else if(G[x][y] == 'A')
        K = true;
}

void result(int x, int y, int N)
{
    if(x < 0 || y < 0 || x >= N || y >= N)
        return;
    if(G[x][y] == '.' || G[x][y] == 'A')
    {
        for(int i = 0; i < k; i++)
        {
            int t = max(max(x - X[i], X[i] - x), max(y - Y[i], Y[i] - y));
            if(max(x - X[i], X[i] - x) == max(y - Y[i], Y[i] - y))
                t++;
            if(t < mini)
                mini = t;
        }
        G[x][y] = 'P';
        result(x+1, y, N);
        result(x, y+1, N);
        result(x-1, y, N);
        result(x, y-1, N);
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int N, M;
    cin >> N >> M;
    int X, Y, X_, Y_;

    for(int i = 0; i < N; i++)
        for(int j = 0; j < N; j++)
        {
            cin >> G[i][j];
            if(G[i][j] == 'A')
            {
                X = i;
                Y = j;
            }
            else if(G[i][j] == 'B')
            {
                X_ = i;
                Y_ = j;
            }
        }

    mark(X_, Y_, N);
    if(K)
        cout << -1;
    else
    {
        result(X, Y, N);
        if(M == 1)
            cout << max(1, mini-1);
        else
            cout << max(1, mini/2);
    }

    return 0;
}