ZOJ 1649 Rescue(BFS)

来源:互联网 发布:视频编辑软件安卓版 编辑:程序博客网 时间:2024/05/19 12:15

Rescue

Time Limit: 2 Seconds Memory Limit: 65536 KB

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<iostream>#include<cstring>#include<queue>#include<algorithm>using namespace std;const int oo=1e9;const int mm=233;const int dx[]={1,-1,0,0};const int dy[]={0,0,1,-1};int mt[mm][mm];char s[mm][mm];class node{  public:int x,y,t;};int w,h,ans,kx,ky,ex,ey;queue<node >q;void bfs(int x,int y,int dep){  int tx,ty;  node xx;xx.x=x;xx.y=y;xx.t=dep;  q.push(xx);  while(!q.empty())  {    xx=q.front();q.pop();    for(int i=0;i<4;i++)    {      tx=xx.x+dx[i];ty=xx.y+dy[i];      if(tx<0||tx>=w||ty<0||ty>=h||s[tx][ty]=='#')continue;      node z;      z.x=tx;z.y=ty;z.t=xx.t+1;      if(s[tx][ty]=='x')z.t++;      if(z.t<mt[tx][ty])mt[tx][ty]=z.t,q.push(z);    }  }}int main(){  while(cin>>w>>h)  {    for(int i=0;i<w;i++)      for(int j=0;j<h;j++)    { mt[i][j]=oo;      cin>>s[i][j];      if(s[i][j]=='a')kx=i,ky=j;      if(s[i][j]=='r')ex=i,ey=j;    }    bfs(kx,ky,0);    if(mt[ex][ey]<oo)cout<<mt[ex][ey]<<"\n";    else cout<<"Poor ANGEL has to stay in the prison all his life.\n";  }}