点击查看代码
#include<bits/stdc++.h>
using namespace std;
char mp[200][200];
struct ty{
int x,y;
int num;
int fx;
bool operator < (const ty&y) const{
return num>y.num;
}
};
int ex,ey;
int sx,sy;
int n;
int vis[200][200][5];
int dx[5] = {0,1,0,-1,0};
int dy[5] = {0,0,1,0,-1};
priority_queue<ty> q;
int bfs(){
q.push({sx,sy,0,0});
while(!q.empty()){
auto op = q.top();
q.pop();
int xx = op.x;
int yy = op.y;
// if(vis[xx][yy][op.fx]) continue;
vis[xx][yy][op.fx] = 1;
if(xx==ex&&yy==ey) return op.num;
for(int i = 1;i<=4;i++){
int nx = xx + dx[i];
int ny = yy + dy[i];
if(mp[nx][ny]!='x'&&!vis[nx][ny][i]&&nx>=1&&nx<=n&&ny>=1&&ny<=n){
if(op.fx==0){
q.push({nx,ny,0,i});
}
else{
if(op.fx==i){
// cout<<nx<<" "<<ny<<endl;
// cout<<op.num<<" !"<<endl;
q.push({nx,ny,op.num,i});
}
else{
q.push({nx,ny,op.num+1,i});
}
}
}
}
}
return -1;
}
int main(){
cin>>n;
// cout<<1<<endl;
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;
}
}
}
memset(vis,0,sizeof(vis));
cout<<bfs();
}