hdojRescue (BFS)

Problem Description
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
题意:angel被关在监狱中,她的朋友们前去营救她,给出一个监狱的布局图,a是angel的位置,r是朋友的位置,x是守卫的位置,如果朋友们在营救过程中碰到了守卫,需要花一单位时间去打败守卫,并且每走一步也要花去一单位时间,求成功营救angel所花费的最少时间
思路:用bfs和优先队列.
代码如下:
#include
#include
#include
#include
using namespace std;
char map[220][220];
int n,m,flag,sx,sy,ex,ey;
int dir[4][2]={0,1,1,0,0,-1,-1,0};
struct node{
	int x,y,step;
    friend	bool operator < (node a,node b)
	{
		return a.step>b.step;
	}
};
int judge(node temp)
{
	if(temp.x>=0&&temp.x=0&&temp.yque;
	que.push(s);
	while(!que.empty())
	{
       node now=que.top();
		que.pop();
		if(now.x==ex&&now.y==ey)
		{
             return now.step;
		}
		for(int l=0;l<4;l++)
		{
			node end;
			end.x=now.x+dir[l][0];
			end.y=now.y+dir[l][1];
             if(judge(end))
             {
             	if(map[end.x][end.y]=='.'||map[end.x][end.y]=='a')
             	end.step=now.step+1;
             	else
             	end.step=now.step+2;
             	map[end.x][end.y]='#';
             	que.push(end);
			 }
		}
		
	}
	return -1;
}
int main()
{
	int i,j;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		if(n==0&&m==0)
		break;
		flag=0;
		for(i=0;i



你可能感兴趣的:(BFS,栈&队列)