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.
Input First line contains two integers stand for N and M.
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
|
翻译:天使被魔法师抓住了!他被Molipy关进了监狱。监狱被描述为一个N*M(N,M<=200)矩阵。监狱里有墙、路和警卫。安琪的朋友想救安琪尔。他们的任务是:接近天使。我们假设“接近天使”是为了到达安琪停留的位置。当网格中有守卫时,我们必须杀死他(或她?)才能进入网格。我们假设我们向上,向下,右边,左边需要1个单位时间,而杀死一个守卫也需要1个单位时间。我们有足够的力量杀死所有的卫兵。你必须计算最小的时间来接近安琪尔。(当然,我们只能向上、下、左和右移动到范围内的邻居网格。)
第一行包含代表N和M的两个整数,然后N行如下,每一行都有M个字符。“.”代表路,“a”代表天使,“r”代表天使的每个朋友。处理到文件的末尾。
对于每个测试用例,您的程序应该输出一个整数,表示所需的最小时间。如果这样的数字不存在,你就应该写出一句“可怜的安琪尔必须一辈子呆在监狱里”的台词。
这道题典型迷宫求解,用bfs或dfs都行,我这里的代码是dfs。
代码:
#include<stdio.h>
#include<string.h>
int vis[1010][1010];
char a[1010][1010];
int m,n,t,ans,step,k,s;
void dfs(int x,int y,int step)//写一个深搜函数
{
if(vis[x][y]||a[x][y]=='#'||step>=ans) return ;条件限定
if(a[x][y]=='r')//从a开始搜索直到找到r为止
{
k=1;
if(step<ans) ans=step;//找到的路径中进行比较得到用时最短的那个
return ;
}
if(a[x][y]=='x')//遇见x时时间多用一秒
{
step++;
}
vis[x][y]=1;//进行深搜
dfs(x+1,y,step+1);
dfs(x-1,y,step+1);
dfs(x,y+1,step+1);
dfs(x,y-1,step+1);
vis[x][y]=0;
}
int main()
{
int i,j,ax,ay;
while(~scanf("%d%d",&m,&n))//输入m,n
{
memset(vis,0,sizeof(vis));//清零
memset(a,'#',sizeof(a));//将地图先都标为#
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf(" %c",&a[i][j]);//输入路径及其他
if(a[i][j]=='a')//找到a所在的位置,记录位置,从这里开始搜索
{
ax=i;
ay=j;
}
}
}
ans=100000;//将得到的答案先赋为最大值,进行比较
k=0;
dfs(ax,ay,0);//深搜
if(k) printf("%d\n",ans);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}