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<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
int book[220][220];
int n,m,x1,y1;
int ne[4][2]={0,1,1,0,-1,0,0,-1};
char s[210][210];
struct node
{
int x,y,step;
bool operator < (const node & b) const
{
return b.step<step;
}
};
int bfs(int x,int y)
{
priority_queue<node>q;
node st,en;
st.x=x;
st.y=y;
st.step=0;
book[x][y]=1;
q.push(st);
while(!q.empty())
{
st=q.top();
q.pop();
if(s[st.x][st.y]=='a')
return st.step;
for(int i=0;i<4;i++)
{
int tx=st.x+ne[i][0];
int ty=st.y+ne[i][1];
if(tx<0||tx>=n||ty<0||ty>=m)
continue;
if(!book[tx][ty]&&s[tx][ty]!='#')
{
en.x=tx;
en.y=ty;
en.step=st.step+1;
book[tx][ty]=1;
if(s[tx][ty]=='x')
en.step+=1;
q.push(en);
}
}
}
return -1;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(book,0,sizeof(book));
int i,j;
for(i=0;i<n;i++)
scanf("%s",s[i]);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
if(s[i][j]=='r')
{
x1=i;
y1=j;
break;
}
}
int f=bfs(x1,y1);
if(f==-1)
printf("Poor ANGEL has to stay in the prison all his life.\n");
else
printf("%d\n",f);
}
}