题目大意:解救天使,但天使有很多朋友,迷宫中也有守卫,求解救天使的最短路径长度,其中任何一个朋友解救到即可,遇到守卫就杀死,并且需要再花费一个时间。
解题思路:由于天使有很多朋友,数量未知,因此,将天使作为起点,对其朋友进行搜索。换需要注意一点的是遇到x的处理方法,可以在搜索过程中路径加1以后,再对该点进行判断,如该点为x,则再加一个长度。详见code。
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1242
code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 200+10;
char map[MAXN][MAXN];
int vis[MAXN][MAXN];
int n,m,sx,sy;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node{
int x,y,step;
};
int BFS(){
node t,s;
queue<node> q;
s.x=sx;s.y=sy;
s.step=0;
q.push(s);
vis[s.x][s.y]=1;
while(!q.empty()){
node temp =q.front();
q.pop();
if(map[temp.x][temp.y]=='r') return temp.step; //找到朋友就返回长度
for(int i=0;i<4;i++){
t.x=temp.x+dir[i][0];
t.y=temp.y+dir[i][1];
t.step=temp.step+1;
if(map[t.x][t.y]=='x') t.step++; //如果遇到x就再加一次
if(t.x>=0 && t.x<n && t.y>=0 && t.y<m && !vis[t.x][t.y] && map[t.x][t.y]!='#'){ //越界和条件判断
vis[t.x][t.y]=1;
q.push(t);
}
}
}
return 0;
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
memset(map,'#',sizeof(map)); //初始化
memset(vis,0,sizeof(vis)); //初始化
for(int i=0;i<n;i++){
scanf("%s",&map[i]);
for(int j=0;j<m;j++){ //由于朋友数量不确定,因此将天使在的点设为起点
if(map[i][j]=='a'){
sx=i;sy=j;
}
}
}
int ans=BFS();
if(!ans) printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n",ans);
}
return 0;
}