因为要求最近距离,所以用Bfs
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int>PII;
int n;
const int N = 110;
char g[N][N];
int vis[N][N];
int dis[N][N];
PII start, End;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
void bfs(PII start) {
queue<PII> q;
q.push(start);
vis[start.first][start.second] = 1; //标记为走过
dis[start.first][start.second] = 0; // 原地不动就是0
while (!q.empty()) {
PII t = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int tx = t.first + dx[i], ty = t.second + dy[i];
if (tx < 1 || tx > n || ty < 1 || ty > n || vis[tx][ty] == 1 || g[tx][ty] == g[t.first][t.second])
continue;
vis[tx][ty] = 1; //标记为走过
dis[tx][ty] = dis[t.first][t.second] + 1; //距离+1
q.push({tx, ty});
}
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> g[i][j];
if (g[i][j] == 'A') {
start = {i, j};
}
if (g[i][j] == 'B') {
End = {i, j};
}
}
}
bfs(start);
if (dis[End.first][End.second])
cout << dis[End.first][End.second] << endl;
else
cout << "-1" << endl;
return 0;
}