F - Rescue 优先队列bfs

时间:2023-03-09 06:26:38
F - Rescue 优先队列bfs

来源poj

Angel was caught by the MOLIGPY! He was put in * by Moligpy. The * is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the *.

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 * all his life."

Sample Input

7 8

.#####.

.a#..r.

..#x...

..#..#.#

...##..

.#......

........

Sample Output

13

和之前坦克大战一模一样

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <iomanip>
#include<cmath>
#include<float.h>
#include<string.h>
#include<algorithm>
#define sf scanf
#define pf printf
#define scf(x) scanf("%d",&x)
#define scff(x,y) scanf("%d%d",&x,&y)
#define prf(x) printf("%d\n",x)
#define mm(x,b) memset((x),(b),sizeof(x))
#include<vector>
#include<queue>
#include<map>
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=a;i>=n;i--)
typedef long long ll;
const ll mod=1e9+7;
const double eps=1e-8;
const int inf=0x3f3f3f3f;
using namespace std;
const double pi=acos(-1.0);
const int N=3e2+10;
char MAP[N][N];
struct node
{
int x,y,ans;
friend bool operator <(node a,node b){ return a.ans>b.ans; }
node(int a=0,int b=0){ x=a;y=b;ans=0; }
};
int a[4][2]={-1,0,1,0,0,1,0,-1};
priority_queue<node>q;
bool checkt(node a)
{
return (MAP[a.x][a.y]=='a');
}
int visit[N][N];
int bfs()
{
node t,tt;
while(!q.empty())
{
t=q.top();
q.pop();
visit[t.x][t.y]=1;
rep(i,0,4)
{
tt.ans=t.ans+1;
tt.x=t.x+a[i][0];
tt.y=t.y+a[i][1];
if(!visit[tt.x][tt.y])
{
if(checkt(tt))
return tt.ans;
if(MAP[tt.x][tt.y]=='.')
q.push(tt);
else if(MAP[tt.x][tt.y]=='x')
{
tt.ans++;
q.push(tt);
}
visit[tt.x][tt.y]=1;
}
}
}
return -1;
}
void display(int n,int m)
{
mm(visit,0);
while(!q.empty()) q.pop();
int x,y;
rep(i,1,n+1)
rep(j,1,m+1)
if(MAP[i][j]=='r')
{ x=i;y=j;}
q.push(node(x,y));
int ans=bfs();
if(ans==-1)
pf("Poor ANGEL has to stay in the * all his life.\n");
else
prf(ans);
}
int main()
{
int n,m;
while(~scff(n,m)&&n&&m)
{
mm(MAP,'#');
rep(i,1,n+1)
{
sf("%s",MAP[i]+1);
MAP[i][m+1]='#';
}
display(n,m);
}
return 0;
}