Rescue

来源:互联网 发布:js裁剪图片并上传 编辑:程序博客网 时间:2024/05/31 13:15

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<iostream>
#include<queue>
using namespace std;
int N,M;
char prison[201][201];
bool isvisit[201][201];
bool cross(int a,int b)
{
   if(a>=0&&a<N&&b>=0&&b<M&&!isvisit[a][b]&&prison[a][b]!='#')
   {
     return true;
   }
   return false;
}
int s1,s2,d1,d2;//起点和终点


typedef struct node{


int a;
int b;
int count;
bool operator<(const node &n2) const
{
 return count>n2.count;
}

}Node;


int totalmin=-1;


int direction[][2]={{-1,0},{0,-1},{0,1},{1,0}};
void bfs()
{
Node start={s1,s2,0};
isvisit[s1][s2]=1;
    priority_queue<Node> myqueue;
myqueue.push(start);
while(!myqueue.empty())
{
  Node last=myqueue.top();
  myqueue.pop();
  int x=last.a;
  int y=last.b;
 // cout<<"x:"<<x<<"y:"<<y<<endl;
  int c=last.count;
  if(prison[x][y]=='r')
  {
     totalmin=c;
 return ;
  }
  for(int i=0;i<4;i++)
  {
    int nx=x+direction[i][0];
int ny=y+direction[i][1];

if(cross(nx,ny))
{
Node now={nx,ny,0};
if(prison[nx][ny]=='x')
{
   now.count=c+2;

}
else
now.count=c+1;
             myqueue.push(now);
isvisit[nx][ny]=1;
}
  }
}

}
int main()
{
   //freopen("in.txt","r",stdin);
   int i,j;
while(cin>>N>>M)
{
   for( i=0;i<N;i++)
{
 for( j=0;j<M;j++)
 {
     cin>>prison[i][j];
 if(prison[i][j]=='a')
 {
   s1=i;
s2=j;
 }
/* if(prison[i][j]=='r')
 {
   d1=i;
d2=j;
 }*/
 }
}

memset(isvisit,false,sizeof(isvisit));
totalmin=-1;
        bfs();
if(totalmin==-1)
{
 cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
else
{
  cout<<totalmin<<endl;
}
}
  return 0;
}


原创粉丝点击