广搜加优先队列 题目: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 Output13该题就是广搜加优先队列,首先应该明白最少步数到达终点的不一定消耗时间最小,因此按最短步数搜到的结果不一定是正确结果,此处应该考虑所用时间最短,因此每次遍历四个方向所有的值要按从小到大排列加入队列,依次往下寻找,到达终点那个值即为其所求的值。 代码:#include
#include
#include
using namespace std;
typedef struct stu{
int x,y,step;
}st;
int cmp(st a,st b)
{
return a.step }
int main()
{
int i,j,k,m,n,x0,y0,x1,y1,v;
char s[210][210];
int a[4][2]={0,1,1,0,-1,0,0,-1};
st s0[100010];
int b[210][210];
while(scanf("%d%d",&m,&n)!=EOF)
{
memset(b,0,sizeof(b));
memset(s,0,sizeof(s));
memset(s0,0,sizeof(s0));
for(i=0;i {
scanf("%s",s[i]);
  for(j=0;j   {
    if(s[i][j]=='a')
      x0=i,y0=j;
    if(s[i][j]=='r')
      x1=i,y1=j;
  }
}
int h,t,nx,ny;
h=t=0;
s0[t].x=x0;
s0[t].y=y0;
s0[t].step=0;
b[x0][y0]=1;
t++;v=0;k=99999;
while(h {
for(i=0;i<4;i++)
{
nx=s0[h].x+a[i][0];
ny=s0[h].y+a[i][1];
if(nx<0||ny<0||nx>=m||ny>=n)
 continue;
if(b[nx][ny]==0&&s[nx][ny]!='#')
{
b[nx][ny]=1;
s0[t].x=nx;
s0[t].y=ny;
if(s[nx][ny]=='x')
s0[t].step=s0[h].step+2;
else
s0[t].step=s0[h].step+1;
       t++;
 }
 if(nx==x1&&ny==y1)
  {
   if(k>s0[t-1].step)
    k=s0[t-1].step;
    v=1;
    break;
  }
}
if(v==1)
 break;
sort(s0,s0+t,cmp);
 h++;
}
for(i=0;i<=k*2*2;i++)
{
printf("%d %d %d\n",s0[i].x,s0[i].y,s0[i].step);
}
if(v==1)
printf("%d\n",k);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}

你可能感兴趣的:(广搜加优先队列 题目:Rescue)