题目大意:给你一个n*m的矩阵,矩阵中’a’代表天使,'r’代表天使的朋友,‘x’代表守卫(虽然题目没说,可以根据样例推理出来),’.‘代表可以走的路,’#'代表不能走的路,每走一步花费1个单位时间,而遇到守卫要花费额外的1个单位时间打败它。
解题思路:很典型的bfs,和我比赛时的另一题差不多。题目要求天使朋友解救天使所花费最小时间,注意,输入样例之中已经明确表示天使朋友不只一位,所以当起点是未知个数,而终点只有一个。如果按照平常的思路,每个起点跑一个bfs,由于起点个数是未知的,所以可能会超时。那么我们可以逆向思维,将天使的位置当作起点,天使朋友的位置当作终点,那么我们就只用跑一次bfs就行了。最后别忘了如果最小值不存在也就是天使无法到达它的任何一个朋友的位置就输出“Poor ANGEL has to stay in the prison all his life.”
代码:
#include <bits/stdc++.h>
using namespace std;
int dis[210][210];
int vis[210][210];
char ma[210][210];
int ax,ay;
int n,m;
const int inf=100000000;
struct node{
int x,y,v;
node(int xx,int yy,int vv){
x=xx;y=yy;v=vv;
}
};
queue<node>q;
void bfs()
{
while(!q.empty())q.pop();
q.push(node(ax,ay,0));
vis[ax][ay]=0;
while(!q.empty()){
node temp=q.front();
q.pop();
dis[temp.x][temp.y]=temp.v;
if(ma[temp.x+1][temp.y]!='#'&&!vis[temp.x+1][temp.y]&&temp.x+1<=n){
if(ma[temp.x+1][temp.y]=='x')q.push(node(temp.x+1,temp.y,temp.v+2));
else q.push(node(temp.x+1,temp.y,temp.v+1));
vis[temp.x+1][temp.y]=1;
}
if(ma[temp.x-1][temp.y]!='#'&&!vis[temp.x-1][temp.y]&&temp.x-1>0){
if(ma[temp.x-1][temp.y]=='x')q.push(node(temp.x-1,temp.y,temp.v+2));
else q.push(node(temp.x-1,temp.y,temp.v+1));
vis[temp.x-1][temp.y]=1;
}
if(ma[temp.x][temp.y+1]!='#'&&!vis[temp.x][temp.y+1]&&temp.y+1<=m){
if(ma[temp.x][temp.y+1]=='x')q.push(node(temp.x,temp.y+1,temp.v+2));
else q.push(node(temp.x,temp.y+1,temp.v+1));
vis[temp.x][temp.y+1]=1;
}
if(ma[temp.x][temp.y-1]!='#'&&!vis[temp.x][temp.y-1]&&temp.y-1>0){
if(ma[temp.x][temp.y-1]=='x')q.push(node(temp.x,temp.y-1,temp.v+2));
else q.push(node(temp.x,temp.y-1,temp.v+1));
vis[temp.x][temp.y-1]=1;
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m)){
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
dis[i][j]=inf;
vis[i][j]=0;
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>ma[i][j];
if(ma[i][j]=='a'){
ax=i;ay=j;
}
}
}
bfs();
int mi=inf;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(ma[i][j]=='r')mi=min(mi,dis[i][j]);
}
}
if(mi==inf) cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
else cout<<mi<<endl;
}
return 0;
}