HDU - 1242 Rescue (dfs基础题)

版权声明:转载请注明出处 https://blog.csdn.net/doubleguy/article/details/82355322

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<bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const int maxn = 300;
char str[maxn][maxn];
int vis[maxn][maxn];
int edx,edy;
int ans;
int n,m;
int to[4][2]={1,0,-1,0,0,1,0,-1};


void dfs(int x,int y,int step)
{
	if(str[x][y]=='x')	step++;
	if(str[x][y]=='r')
	{
		if(step<ans)
			ans=step;
		return;
	}
	for(int i=0;i<4;i++)
	{
		int x1=x+to[i][0];
		int y1=y+to[i][1];
		if(x1>=0&&x1<n&&y1>=0&&y1<m&&!vis[x1][y1]&&str[x1][y1]!='#')
		{
			vis[x1][y1]=1;	
			dfs(x1,y1,step+1);
			vis[x1][y1]=0;//此处不能省略,它代表的含义是当此路不通,或找到结果后尝试看看会不会有其他路耗时更短
		}
	}
}

int main()
{
	int stx,sty;
	while(~scanf("%d%d",&n,&m))
	{
		memset(vis,0,sizeof(vis));
		ans=INF;
		for(int i=0;i<n;i++)
		{
			scanf("%s",str[i]);
			for(int j=0;j<m;j++)
			{
				if(str[i][j]=='a')
				{
					stx=i;
					sty=j;
					break;
				}
			}
		}
		vis[stx][sty]=1;
		dfs(stx,sty,0);
		if(ans!=INF)	
			printf("%d\n",ans);
		else
			printf("Poor ANGEL has to stay in the prison all his life.\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/doubleguy/article/details/82355322