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.)
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.
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<bits/stdc++.h>
using namespace std;
char z[210][210];
int dx[4]={-1,1,0,0},dy[4]={0,0,-1,1},n,m,a,b,flag,vis[210][210];
struct pp
{
int x,y,s;
};
bool operator<(const pp&a,const pp&b)
{
return a.s>b.s;
}
priority_queue<pp>q;
void bfs()
{
pp p,h;
p.x=a;
p.y=b;
p.s=0;
q.push(p);
while(!q.empty())
{
p=q.top();q.pop();
if(z[p.x][p.y]=='a')
{
flag=0;
cout<<p.s<<endl;
return;
}
for(int i=0;i<4;i++)
{
h.x=p.x+dx[i];
h.y=p.y+dy[i];
h.s=p.s+1;
if(h.x>=0&&h.x<n&&h.y>=0&&h.y<m&&!vis[h.x][h.y]&&z[h.x][h.y]!='#')
{
if(z[h.x][h.y]=='x')
h.s++;
vis[h.x][h.y]=1;
q.push(h);
}
}
}
}
int main()
{
while(cin>>n>>m)
{
memset(vis,0,sizeof(vis));
flag=1;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
cin>>z[i][j];
if(z[i][j]=='r')
{
a=i;
b=j;
}
}
bfs();
if(flag)
cout<<"Poor ANGEL has to stay in the prison all his life.\n";
while(!q.empty())
q.pop();
}
return 0;
}
本文介绍了一个基于优先队列实现的广度优先搜索算法,用于解决一个救援任务问题。任务目标是在一个由墙壁、道路和守卫组成的矩阵监狱中找到到达被囚禁朋友位置所需的最短时间。
317

被折叠的 条评论
为什么被折叠?



