hdu 1242 Rescue(BFS)(犯晕)

来源:互联网 发布:国密算法 java实现 编辑:程序博客网 时间:2024/05/30 23:04
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
广搜+优先队列:
#include<cstdio>  #include<cstring>  #include<queue>  using namespace std;int n,m,sx,sy,ex,ey;char c[210][210];int px[4]={0,0,1,-1};  //方向 int py[4]={1,-1,0,0};struct st{int x,y;int step;friend bool operator <(st a,st b)  //优先队列 {return a.step>b.step;} };void bfs(){int flag=0,i;st now,next; now.x=sx;now.y=sy;now.step=0;priority_queue<st>q; q.push(now);while(!q.empty()){next=q.top();//now=q.top()就错啊,不知道为啥,不能和前一个相同,因为判断的时候为next判断,所以不能不用nowq.pop();if(next.x==ex&&next.y==ey){flag=1;break;}for(i=0;i<4;i++){now.x=next.x+px[i];now.y=next.y+py[i];if(now.x>=0&&now.x<n&&now.y>=0&&now.y<m&&c[now.x][now.y]!='#'){if(c[now.x][now.y]=='x')  now.step=next.step+2;else   now.step=next.step+1;c[now.x][now.y]='#';q.push(now);}}}if(flag)printf("%d\n",next.step);  //和上面的对应else printf("Poor ANGEL has to stay in the prison all his life.\n"); //也不能放到主函数里 }int main(){int i,j;while(scanf("%d%d",&n,&m)!=EOF){for(i=0;i<n;i++){   getchar();   for(j=0;j<m;j++)   {     scanf("%c",&c[i][j]);     if(c[i][j]=='r')     {       sx=i;       sy=j;  }  if(c[i][j]=='a')  {    ex=i;    ey=j;  }   }} bfs();}return 0;}

0 0
原创粉丝点击