#include<bits/stdc++.h>
using namespace std;
int N,m;
char polje[505][505];
bool markirali[505][505],Au=0,Bu=0;
void markiraj(int i, int j, char m, int pi, int pj) {
    if(i>N or j>N or i<1 or j<1 or polje[i][j]=='X' or markirali[i][j])
        return;
    if((polje[i][j]=='A' and m=='B')or(polje[i][j]=='B' and m=='A')) {
        cout<<0<<endl;
        exit(0);
    }
    //cout<<i<<" "<<j<<endl;
    polje[i][j]=m;
    markirali[i][j]=1;
    markiraj(i+1,j,m,i,j);
    markiraj(i-1,j,m,i,j);
    markiraj(i,j+1,m,i,j);
    markiraj(i,j-1,m,i,j);
    return;
}

int main() {
    cin>>N>>m;
    for(int i=1;i<=N;i++)
        for(int j=1;j<=N;j++)
            cin>>polje[i][j];
    for(int i=1;i<=N and !(Au and Bu);i++)
        for(int j=1;j<=N and !(Au and Bu);j++)
            if(polje[i][j]=='A') {
                for(int d=1;d<=N;d++)
                    for(int k=1;k<=d;k++)
                        markirali[d][k]=0;
                markiraj(i,j,'A',i,j);
                Au=1;
            }
            else
                if(polje[i][j]=='B') {
                    for(int d=1;d<=N;d++)
                    for(int k=1;k<=d;k++)
                        markirali[d][k]=0;
                    markiraj(i,j,'B',i,j);
                    Bu=1;
                }


    return 0;
}