#include<bits/stdc++.h>
using namespace std;
const int N = 1005;
char a[N][N];
int n ;
int st[N][N];
bool f ;
int sx , sy , ans = 0x3f3f3f3f, sum;
int dx[4] = { 0 , 0 , 1 , -1 };
int dy[4] = { 1 , -1 , 0 , 0 };
void dfs(int x , int y , int dir , int k){
if(k >= ans)return ;
if( x == sx && y == sy){
ans = min ( ans , k );
f = 1;
return;
}
st[x][y] = -1;
for(int i = 0 ; i < 4 ; i ++ ){
int nx = dx[i] + x ;
int ny = dy[i] + y ;
if( nx < 1 || ny < 1 || nx > n || ny > n || st[nx][ny] == -1)continue ;
if( nx >= 1 && ny >= 1 && nx <= n && ny <= n && st[nx][ny] == 0 ){
st[nx][ny] = -1;
int t = 0;
if(dir != i)t = 1;
if(dir == 4)t = 0;
dfs( nx , ny , i , k + t);
st[nx][ny] = 0 ;
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
int x , y ;
for(int i = 1 ; i <= n ; i ++){
for(int j = 1 ; j <= n ; j ++){
cin >> a[i][j];
if(a[i][j] == 'A'){
x = i ;
y = j ;
st[i][j] = -1 ;
}
if(a[i][j] == 'B'){
sx = i ;
sy = j ;
st[i][j] = 0 ;
}
if(a[i][j] == 'x'){
st[i][j] = -1;
}
}
}
dfs( x , y , 4 , 0);
if(f)cout << ans;
else cout << -1;
return 0;
}