#include<stdio.h>

char grad[500][500];
int n,m;
int starti,startj,endi,endj;

struct Point{
    int i,j;
};

bool Imaputa(Point start,Point kraj){
    if(start.i==kraj.i && start.j==kraj.j) return true;
    else for(int i=0;i<4;i++)
        switch(i){
            case 0:if(grad[start.i+1][start.j]!='X')start.i++;Imaputa(start,kraj);
            case 1:if(grad[start.i][start.j+1]!='X')start.j++;Imaputa(start,kraj);
            case 2:if(grad[start.i-1][start.j]!='X')start.i--;Imaputa(start,kraj);
            case 3:if(grad[start.i][start.j-1]!='X')start.j--;Imaputa(start,kraj);
        }
    return false;
}

int main(){

    scanf("%d%d",&n,&m);
    
    Point start,endi;
    
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++){
            scanf("%c",&grad[i][j]);
            if(grad[i][j]=='A'){
                start.i=i;
                start.j=j;
            }
            else if(grad[i][j]=='B'){
                endi.i=i;
                endi.j=j;
            }
        }
    
    if(Imaputa(start,endi))printf("-1");
    
    return 0;
}