vjudge-Rescue (bfs)

Rescue

 


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到a需要最少的步数,其中x需要两步,我在处理x时是先把它转化为.然后放到队列尾。

程序代码:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
struct data{
	int x;
	int y;
};
int main()
{
	char a[210][210];
	int m,n,i,j,k,tx,ty;
	int book[210][210];
	queue<data>que;
	data A,B;	
	while(scanf("%d%d",&m,&n)!=EOF)
	{
		memset(book,0,sizeof(book));
		for(i=0;i<m;i++)
			for(j=0;j<n;j++)
			{
				scanf(" %c",&a[i][j]);
				if(a[i][j]=='r')
				{
					A.x=i;
					A.y=j;
				}
			}
		que.push(A);
		while(!que.empty())
		{
			A=que.front();
			que.pop();
			if(a[A.x][A.y]=='x')
			{
				a[A.x][A.y]='.';
				que.push(A);
				book[A.x][A.y]++;
				continue;
			}
			int next[4][2]={0,1, 0,-1, 1,0, -1,0};
			for(k=0;k<4;k++)
			{
				tx=A.x+next[k][0];
				ty=A.y+next[k][1];
				if(tx<0||tx>=m||ty<0||ty>=n||a[tx][ty]=='#'||book[tx][ty]!=0)
					continue;
				B.x=tx;
				B.y=ty;
				que.push(B);
				book[tx][ty]=book[A.x][A.y]+1;
			}
		}
		for(i=0;i<m;i++)
			for(j=0;j<n;j++)
				if(a[i][j]=='a')
				{
					if(book[i][j]==0)
						printf("Poor ANGEL has to stay in the prison all his life.\n");
					else
						printf("%d\n",book[i][j]);
				}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/HeZhiYing_/article/details/81066269
BFS
今日推荐