Rescue (BFS+优先队列)

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

题意:r上下左右移动要一分钟,遇到x需要多加一分钟,求r到a所需的时间。

#include<cstdio>
#include<stack>
#include<queue>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
int d[205][205]={0};
typedef pair<int,int> P;
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
struct node{
	int x,y;
	friend bool operator < (node a,node b){
		return d[a.x][a.y]>d[b.x][b.y];
	}
};
int main(){
	int N,M,sx,sy,ex,ey;
	while(scanf("%d%d",&N,&M)!=EOF){
		char maze[N+5][M+5];
		memset(d,0,sizeof(d));
		for(int i=0;i<N;i++){
			for(int j=0;j<=M;j++){
				scanf("%c",&maze[i][j]);
				if(maze[i][j]=='r'){
					sx=i;
					sy=j;
				}
				if(maze[i][j]=='a'){
					ex=i;
					ey=j;
				}
			}
		}
		priority_queue<node> que;
		node ans;
		ans.x=sx;
		ans.y=sy;
		que.push(ans);
		while(que.size()){
			node p=que.top();
			que.pop();
			if(p.x==ex&&p.y==ey){
				break;
			}
			for(int i=0;i<4;i++){
				int nx=p.x+dx[i],ny=p.y+dy[i];
				if(nx>=0&&nx<N&&ny>=0&&ny<M&&d[nx][ny]==0&&maze[nx][ny]!='#'){
					if(maze[nx][ny]=='x'){
						d[nx][ny]=d[p.x][p.y]+2;
					}
					else d[nx][ny]=d[p.x][p.y]+1;
					ans.x=nx;
					ans.y=ny;
					que.push(ans);
				}
			}
		}
		if(d[ex][ey]==0){
			printf("Poor ANGEL has to stay in the prison all his life.\n");
		}
		else printf("%d\n",d[ex][ey]);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/miku531/article/details/81320173
今日推荐