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

ps:这道题,说实话,第一时间想到的肯定是用广搜做,但是用深搜做了之后发现有一个有意思的现象,题目中的friend是一个复数,也就说,不止一个朋友,那么,如果用深搜从'r’开始找‘a’,就会超时(也算是一个坑点吧),这个时候,我们就可以用你逆向思维了,用‘a’去找‘r’,碰到第一个‘r’的过程中的最短路径就是我们要得到的答案。

代码如下:

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
int n,m,ii,jj,vis[250][250],ok,ans;
char s[250][250];
void dfs(int x,int y,int step)
{
    if(x<0||x>n-1||y<0||y>m-1||vis[x][y]==1||s[x][y]=='#') return ;
    if(step>=ans)
        return ;//剪枝
    if(s[x][y]=='r')
    {
        ok=1;
        ans=min(step,ans);
        return ;
    }
    if(s[x][y]=='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()
{
    while(~scanf("%d%d",&n,&m))
    {
        memset(vis,0,sizeof(vis));
        for(int i=0; i<n; i++)
            scanf("%s",s[i]);
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                if(s[i][j]=='a')
                {
                    ii=i;
                    jj=j;
                    break;
                }
            }
        }
        ok=0;
        ans=999999999;
        dfs(ii,jj,0);
        if(ok)
            printf("%d\n",ans);
        else printf("Poor ANGEL has to stay in the prison all his life.\n");
    }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页