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");
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章