hdu 1242 Rescue 搜索 bfs 优先队列

Rescue

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 22019    Accepted Submission(s): 7839


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
 
题意:a到r的最短路;
题解:因为有x的存在,原来bfs用普通队列可以满足走一步用1时间,现在x是加2时间,所以要用优先队列保证最短路
代码:
#include 
#include 
#include 
#include 
using namespace std;
int n, m;
int sx, sy;
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
char maps[210][210];
int vis[210][210];
int judge(int x, int y)
{
	if(x<1 || x>n || y<1 || y>m || maps[x][y]=='#')
		return 0;
	return 1;	
} 
struct node{
	int x, y, t;
 	friend bool operator<(node a,node b){
        return a.t>b.t;
    }
};
int bfs()
{
	node now, next;
	priority_queue qu;
	while(!qu.empty()) qu.pop();
	now.x = sx;
	now.y = sy;
	now.t = 0;
	qu.push(now);
	vis[sx][sy] = 1;
	while(!qu.empty())
	{
		now = qu.top();
		qu.pop();
		if(maps[now.x][now.y]=='r')
		{
			return now.t;
		}
		for(int i = 0;i < 4;i++)
		{
			next.x = now.x + dx[i];
			next.y = now.y + dy[i];
			if(judge(next.x,next.y) && !vis[next.x][next.y])
			{
				if(maps[next.x][next.y]=='x') next.t = now.t + 2;
				else next.t = now.t + 1;
				vis[next.x][next.y] = 1;
				qu.push(next);
				
			}
		}
	}
	return -1;
}

int main()
{
	int i, j;
	while(~scanf("%d%d", &n ,&m))
	{
		char str[210];
		memset(vis,0,sizeof(vis));
		for(i = 1;i <= n;i++)
		{
			scanf("%s", str);
			for(j = 1;j <= m;j++)
			{
				maps[i][j] = str[j- 1];
				if(maps[i][j]=='a')
				{
					sx = i;
					sy = j;
				}
			}
		}
		int ans = bfs();
		if(ans==-1)
		{
			printf("Poor ANGEL has to stay in the prison all his life.\n");
		}
		else
		{
			printf("%d\n",ans);
		}
	}
}

你可能感兴趣的:(ACM)