您的位置:首页 > 产品设计 > UI/UE

Hdoj 1242 Rescue

2018-03-16 14:13 295 查看
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

Author

CHEN, Xue

Source

ZOJ Monthly, October 2003

题目分析

r可能会有很多个但是a一定只有一个,从a点开始bfs就可以了,注意干掉一个guard是+2,要用优先队列

Code

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cctype>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;
const int dx[4]={0,-1,0,1};
const int dy[4]={-1,0,1,0};
struct node
{
int x,y,step;
friend bool operator < (const node &a,const node &b)
{
return a.step>b.step;
}
};
node st,ed,now,next;
int n,m,ans;
char map[201][201];
bool vis[201][201];
bool judge(int x,int y)
{
if(x>0 && x<=n && y>0 && y<=m && map[x][y]!='#')
return true;
return false;
}
int bfs()
{
node now,next;
priority_queue<node>q;
memset(vis,false,sizeof(vis));
if(st.x==ed.x && st.y==ed.y) return 0;
q.push(st);
vis[st.x][st.y]=true;
while(!q.empty())
{
now=q.top();
q.pop();
if(map[now.x][now.y]=='r') return now.step;
for(int i=0;i<4;i++)
{
next.x=now.x+dx[i];
next.y=now.y+dy[i];
if(judge(next.x,next.y))
{
if(!vis[next.x][next.y])
{
if(map[next.x][next.y]=='.' || map[next.x][next.y]=='r') next.step=now.step+1;
else next.step = now.step+2;
vis[next.x][next.y]=true;
q.push(next);
}
}
}
}
return -1;
}
int main()
{
while(cin>>n>>m)
{
memset(vis,false,sizeof(vis));
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
cin>>map[i][j];
if(map[i][j]=='a')
{
st.x = i; st.y = j; st.step = 0;
}
}
ans = bfs();
if(ans==-1)
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
else cout<<ans<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: