简单BFS
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <map>
using namespace std;
const int N = 110;
struct Node{
int x,y;
};
char f[N][N];
int n;
int dx[4] = {0,0,-1,1},dy[4] = {1,-1,0,0};
int bfs(Node start){
queue<Node> Q;
Q.push(start);
int dist[N][N];
memset(dist,0,sizeof dist);
dist[start.x][start.y] = 0;
while(!Q.empty()){
auto t = Q.front();
Q.pop();
int distance = dist[t.x][t.y];
if(f[t.x][t.y] == 'B')return distance;
for(int i = 0;i < 4;i++){
int nx = t.x + dx[i];
int ny = t.y + dy[i];
if(nx <= 0 || nx > n || ny <= 0 || ny > n)continue;
if(f[t.x][t.y] == f[nx][ny])continue;//如果是与上面的相同则不去
if(dist[nx][ny] == 0){
Node news;
news.x = nx,news.y = ny;
dist[nx][ny] = distance + 1;
Q.push(news);
}
}
}
return -1;
}
int main(){
cin >> n;
Node start;
for(int i = 1;i <= n;i++){
for(int j = 1;j <= n;j++){
cin >> f[i][j];
if(f[i][j] == 'A')start.x = i,start.y = j;
}
}
cout << bfs(start) << endl;
return 0;
}