#include <bits/stdc++.h>
using namespace std;
const int N = 105;
int n;
char mp[N][N];
int sx,sy,ex,ey;
bool vis[N][N][N];
int dirx[] = {0,0,0,1,-1};
int diry[] = {0,1,-1,0,0};
int bfs() {
queue<int> q;
for(int i = 1;i <= 4;i++) {
q.push(sx);
q.push(sy);
q.push(0);
q.push(i);
vis[sx][sy][i] = 1;
}
while(!q.empty()) {
int x = q.front();q.pop();
int y = q.front();q.pop();
int d = q.front();q.pop();
int c = q.front();q.pop();
// printf("%d %d %d %d %d\n",x,y,d,dirx[c],diry[c]);
if(x==ex&&y==ey) return d;
for(int i = 1;i <= 4;i++) {
int tx,ty;
if(i==c) {
tx = x+dirx[i];
ty = y+diry[i];
if(tx<1||tx>n||ty<1||ty>n||mp[tx][ty]=='x') continue;
if(vis[tx][ty][i]) continue;
q.push(tx);
q.push(ty);
q.push(d+1);
q.push(i);
vis[tx][ty][i] = 1;
} else {
tx = x;
ty = y;
if(vis[tx][ty][i]) continue;
q.push(tx);
q.push(ty);
q.push(d+1);
q.push(i);
vis[tx][ty][i] = 1;
}
}
}
return -1;
}
int main() {
cin >> n;
for(int i = 1;i <= n;i++) {
for(int j = 1;j <= n;j++) {
cin >> mp[i][j];
if(mp[i][j]=='A') sx=i,sy=j;
if(mp[i][j]=='B') ex=i,ey=j;
}
}
cout << bfs() << endl;
}
1 个赞
这是哪道题啊
3 个赞
只是代码曲线像而已
3 个赞