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

思路:这是一道广搜题,题目问天使的朋友在杀死有限个士兵的情况下能否江天使解救出来,这道题还用到了优先队列,就是求出在可以不杀死士兵或者杀死士兵都能救出天使的情况下花费时间最少的那种情况。

#include<stdio.h>
#include<queue> 
#include<string.h>
#include<algorithm>
using namespace std;
int book[220][220];
int n,m,x1,y1;
int ne[4][2]={0,1,1,0,-1,0,0,-1};
char s[210][210];
struct node
{
	int x,y,step;
	 bool operator < (const node & b) const
    {
        return b.step<step;
    }
};
int bfs(int x,int y)
{
	priority_queue<node>q;
	node st,en;
	st.x=x;
	st.y=y;
	st.step=0;
	book[x][y]=1;
	q.push(st);
	while(!q.empty())
	{
		st=q.top();
		q.pop();
		if(s[st.x][st.y]=='a')
		   return st.step;
		for(int i=0;i<4;i++)
		{
			int tx=st.x+ne[i][0];
			int ty=st.y+ne[i][1];
			if(tx<0||tx>=n||ty<0||ty>=m)
			   continue;
			if(!book[tx][ty]&&s[tx][ty]!='#')
			{
				en.x=tx;
				en.y=ty;
				en.step=st.step+1;
				book[tx][ty]=1;
				if(s[tx][ty]=='x')
				  en.step+=1;
				  q.push(en);
			}
		}
	}
	return -1;
}
int main()
{
	while(~scanf("%d%d",&n,&m))
	{
		memset(book,0,sizeof(book));
		int i,j;
		for(i=0;i<n;i++)
	      scanf("%s",s[i]);
	      for(i=0;i<n;i++)
			for(j=0;j<m;j++)
			  {
			  	if(s[i][j]=='r')
			  	   {
			  	   	 x1=i;
			  	   	 y1=j;
			  	   	 break;
				   }
			  }
		 int f=bfs(x1,y1);
		if(f==-1)
		  printf("Poor ANGEL has to stay in the prison all his life.\n");
		 else
		  printf("%d\n",f);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值