杭电1242Rescue(bfs)

Rescue
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit  Status

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
 有多个起点,即天使的朋友位置,一个终点即天使的位置,所以可以以天使的位置为起点进行广搜,又因为遇到守卫需要花费时间杀掉他,走一个格时间也因此不同,使用优先队列
#include
#include
#include
#include
using namespace std;
int visit[210][210];
char map[210][210];
int n,m;
int starx,stary;
struct node{
int x;
int y;
int time;
};
int dir[4][2]={1,0,-1,0,0,1,0,-1};
bool operator< (const node &x,const node &y)
{
return x.time>y.time;
}
int judge(int x,int y)
{
if(x<0||x>=m||y<0||y>=n||visit[x][y]||map[x][y]=='#')
return 0;
return 1;
}
void bfs()
{
node star,end;
priority_queueq;
star.x=starx;
star.y=stary;
star.time=0;
memset(visit,0,sizeof(visit));
visit[star.x][star.y]=1;
q.push(star);
while(!q.empty())
{
star=q.top();
q.pop();
if(map[star.x][star.y]=='r')
{
printf("%d\n",star.time);
return;
}
else
{
for(int i=0;i<4;i++)
{
end.x=star.x+dir[i][0];
end.y=star.y+dir[i][1];
if(judge(end.x,end.y))
{
visit[end.x][end.y]=1;
if(map[end.x][end.y]=='x')
end.time=star.time+2;
else
end.time=star.time+1;
q.push(end);
}
}
}
}
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main()
{
int i,j;
while(~scanf("%d%d",&m,&n))
{
for(i=0;i {
scanf("%s",map[i]);
for(j=0;j if(map[i][j]=='a')
{
starx=i;
stary=j;
map[i][j]='#';
}
}
bfs();
}
return 0;
}




你可能感兴趣的:(bfs)