标签:
Rescue
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 20225 Accepted Submission(s): 7223
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
//我真是弱爆了,一个x写成大写调试了N久才出来,都是泪啊。。。 bfs+优先队列
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
int n,m,stax,stay,stox,stoy;
char ma[210][210];
bool vis[210][210];
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct Node
{
int x,y,step;
friend bool operator <(const Node &a,const Node &b)
{
return a.step>b.step;
}
};
int bfs(int xx,int yy)
{
priority_queue <Node> q;
memset(vis,0,sizeof(vis));
Node a;
a.x=xx,a.y=yy,a.step=0;
q.push(a);
while(!q.empty())
{
Node b=q.top();
q.pop();
vis[b.x][b.y]=1;
if(b.x==stox&&b.y==stoy) return b.step;
for(int i=0;i<4;i++)
{
Node c=b;
c.x+=dir[i][0];
c.y+=dir[i][1];
if(ma[c.x][c.y]=='x')
c.step+=2;
else
c.step++;
if(c.x>=0&&c.x<n&&c.y>=0&&c.y<m&&ma[c.x][c.y]!='#'&&!vis[c.x][c.y])
{
q.push(c);
vis[c.x][c.y]=1;
}
}
}
return -1;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
stox=-1,stoy=-1;
for(int i=0;i<n;i++)
{
scanf("%s",ma[i]);
}
for(int i=0;i<n;i++)
{
for(int k=0;k<m;k++)
{
if(ma[i][k]=='r')
{
stax=i;
stay=k;
}
if(ma[i][k]=='a')
{
stox=i;
stoy=k;
}
}
}
int cnt=bfs(stax,stay);
if(cnt!=-1)
printf("%d\n",cnt);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
版权声明:本文为博主原创文章,未经博主允许不得转载。
HDU 1242
标签:
原文地址:http://blog.csdn.net/a73265/article/details/46860463