您的位置:首页 > 其它

HDU 1242 BFS

2015-09-18 20:46 197 查看

Rescue

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 22045    Accepted Submission(s): 7844


[align=left]Problem Description[/align]
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.)

 

[align=left]Input[/align]
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.

 

[align=left]Output[/align]
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."

 

[align=left]Sample Input[/align]

7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........

 

[align=left]Sample Output[/align]

13

 一定要全执行完。。先到达的不一定是最小。。

#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#define INF 99999
using namespace std;
char map[205][205];
int d[205][205];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
int x01=0,y01=0;
int x11=0,y11=0;
typedef struct node
{
int x=0,y=0;
};
int main()
{
int n=0,m=0;
while(scanf("%d%d",&n,&m)!=EOF)
{
getchar();
memset(d,0,sizeof(d));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='a')
{
x01=i;
y01=j;
}
else if(map[i][j]=='r')
{
x11=i;
y11=j;
}
d[i][j]=INF;
}
getchar();
}
queue<node> q;
d[x01][y01]=0;
node p;
p.x=x01;
p.y=y01;
q.push(p);
while(q.size())
{
node p1=q.front();
q.pop();
/*if(map[p1.x][p1.y]=='r')
{
x11=p1.x;
y11=p1.y;
break;
}*/
for(int i=0;i<4;i++)
{
int dx=p1.x+dir[i][0];
int dy=p1.y+dir[i][1];
if(dx>=1&&dx<=n&&dy>=1&&dy<=m&&map[dx][dy]!='#')
{
int d1=0;
if(map[dx][dy]=='x')
{
d1=d[p1.x][p1.y]+2;
}
else
{
d1=d[p1.x][p1.y]+1;
}
if(d1>=d[dx][dy])
{
continue;
}
d[dx][dy]=d1;
node p2;
p2.x=dx;
p2.y=dy;
q.push(p2);
}
}
}
if(d[x11][y11]!=INF)
printf("%d\n",d[x11][y11]);
else
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: