HDU - 1242 Rescue

Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison. 

Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards. 

You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.) 

 

Input

First line contains two integers stand for N and M. 

Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend. 

Process to the end of the file. 

 

Output

For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing "Poor ANGEL has to stay in the prison all his life." 

 

Sample Input

7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........

 

Sample Output

13

题目大意:天使被监禁了,天使的许多个朋友在找天使,天使的朋友每一次上,下,左,右移动需要1s,遇到守卫时,杀死守卫需要1s,所以遇到守卫一共需要2s,问天使的朋友找到天使所需的最短时间(.代表道路,x代表守卫,a代表天使,r代表天使的朋友,x代表卫兵)。

解题思路:最短路径遍历图优先使用bfs,因为bfs是按照层次进行遍历的,所以当找到天使时一定是最快找到的,但是当遇到守卫时需要所花费1s,所以就不能用简单的队列来做了,使用优先队列来做,当遇到守卫时,这时有守卫的节点就会被放到下一层次进行访问,这样最终保证遇到天使时所需的时间最短,因为有多个朋友,只有一个天使,所以让天使找朋友比较简单

AC代码:

#include
#include
#include
using namespace std;
const int maxn=250;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
int vis[maxn][maxn];
char map[maxn][maxn];
int m,n,ans;
struct node{
	int x,y,time;
	bool friend operator<(node a,node b)
	{
		return a.time>b.time;//用时少的优先级高 
	}
};
void bfs(node s)
{
	node now,nextt;
	priority_queueq; 
	s.time=0;
	q.push(s);
	vis[s.y][s.x]=1;
	while(!q.empty())
	{
		now=q.top();
		q.pop();
		for(int i=0;i<4;i++)
		{
			nextt.x=now.x+dir[i][0];
			nextt.y=now.y+dir[i][1];
			if(nextt.x<0||nextt.x>=m||nextt.y<0||nextt.y>=n||vis[nextt.y][nextt.x]||map[nextt.y][nextt.x]=='#')
				continue;
			nextt.time=now.time+1;//先加加一 
			if(map[nextt.y][nextt.x]=='r')
			{
				cout<>n>>m)
	{
		memset(vis,0,sizeof(vis)); 
		for(int i=0;i>map[i][j];
				if(map[i][j]=='a')//记录天使的位置 
				{
					s.x=j;
					s.y=i;
				}
			}
		}
		bfs(s);
	}
	return 0;
} 

 

你可能感兴趣的:(BFS,图论)