由于边权有\(1\)和\(2\)两种情况,所以就不能用裸的\(BFS\)了,改成优先队列\(BFS\)(其实就是\(dijkstra\))。
const int N=210;
struct Node
{
int dis;
int x,y;
bool operator>(const Node &W) const
{
return dis>W.dis;
}
};
char g[N][N];
int dist[N][N];
bool vis[N][N];
int n,m;
PII st,ed;
bool check(int x,int y)
{
return x>=0 && x<n && y>=0 && y<m;
}
int bfs()
{
memset(dist,0x3f,sizeof dist);
memset(vis,0,sizeof vis);
priority_queue<Node,vector<Node>,greater<Node> > heap;
dist[st.fi][st.se]=0;
heap.push({0,st.fi,st.se});
while(heap.size())
{
Node t=heap.top();
heap.pop();
if(t.x == ed.fi && t.y == ed.se) return dist[t.x][t.y];
if(vis[t.x][t.y]) continue;
vis[t.x][t.y]=true;
for(int i=0;i<4;i++)
{
int a=t.x+dx[i],b=t.y+dy[i];
if(!check(a,b) || g[a][b] == '#') continue;
if(g[a][b] == 'x')
{
if(dist[a][b]>dist[t.x][t.y]+2)
{
dist[a][b]=dist[t.x][t.y]+2;
heap.push({dist[a][b],a,b});
}
}
else
{
if(dist[a][b]>dist[t.x][t.y]+1)
{
dist[a][b]=dist[t.x][t.y]+1;
heap.push({dist[a][b],a,b});
}
}
}
}
return -1;
}
int main()
{
while(cin>>n>>m)
{
for(int i=0;i<n;i++) scanf("%s",&g[i]);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
if(g[i][j] == 'r') st={i,j};
if(g[i][j] == 'a') ed={i,j};
}
int t=bfs();
if(t == -1) puts("Poor ANGEL has to stay in the prison all his life.");
else cout<<t<<endl;
}
//system("pause");
}