#include <iostream>

using namespace std;

int main()
{
    int n,m,i,j,ax,ay,bx,by,mx=501,my=501,p1=0,p2=0,k;
    cin >> n >> m;
    char matr[n][n];
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        {
            cin >> matr[i][j];
            if(matr[i][j] == 'A')
            {
                ax = i;
                ay = j;
            }
            if(matr[i][j] == 'B')
            {
                bx = i;
                by = j;
            }
        }
    for(i=0;i<n;i++)
    {
        for(j=ax;j<bx;j++)
        {
            if(matr[i][j] == 'X')
                p1++;
        }
        if(p1 < mx)
        {
            mx = p1;
            p1 = 0;
        }
        for(j=ay;j<by;j++)
        {
            if(matr[j][i] == 'X')
                p2++;
        }
        if(p2 < my)
        {
            my = p1;
            p2 = 0;
        }
    }
    if(mx > my)
    {
        if(mx % 2 == 0)
            k = mx / 2;
        else
            k = (mx-1)/2;
    }
    else
        if(my % 2 == 0)
            k = my / 2;
        else
            k = (my-1)/2;
    cout << k;
    return 0;
}