杭电1242

来源:互联网 发布:在ubuntu上下载软件 编辑:程序博客网 时间:2024/06/03 18:45

Rescue
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 31239 Accepted Submission(s): 10956

Problem Description
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.”

老规矩先说题目大意,一个天使被坏人抓走了,关在了牢房里,牢房是一个n*m的一块方形区域现在他的朋友要去救他,每移动一个需要一秒,;牢房里有守卫,假设天使的朋友十分强大,能打过任何一个守卫,不过要花费1秒,问最短的时间能将天使救出来,注意天使的朋友不一定只有一个,所以我们这题就不能将天使的朋友作为起点,而要将天使作为起点,进行深搜。下面是AC的代码

#include"iostream"#include"cstdio"int d[4][2]= {0,1,0,-1,1,0,-1,0},n,m,T;char a[205][205];//保存地图int b[205][205];//标志该点有没有被走过void dfs(int x,int y,int time)//当前点的位置,以及到这的时间{    int nx,ny,i;    if(a[x][y]=='r'&&time<T)//若此点为r即天使找到了他的朋友    {//并且时间比最短时间短        T=time;        return;    }    if(time>=T)//若到达这一点的时间不小于最短时间,则没必要继续        return;    for(i=0; i<4; i++)//深搜常规方法    {        nx=x+d[i][0];        ny=y+d[i][1];        if(nx<0||nx>=n||ny<0||ny>=m||a[nx][ny]=='#'||b[nx][ny])            continue;        b[nx][ny]=1;        if(a[x][y]=='x')//因为有守卫,要多花费1秒            dfs(nx,ny,time+2);        else            dfs(nx,ny,time+1);        b[nx][ny]=0;    }}int main(){    int sx,sy,i,j;    while(~scanf("%d%d",&n,&m))    {        getchar();        for(i=0; i<n; i++)            for(j=0; j<m; j++)                b[i][j]=0;        for(i=0; i<n; i++)            gets(a[i]);        for(i=0; i<n; i++)            for(j=0; j<m; j++)                if(a[i][j]=='a')                {                    sx=i;                    sy=j;                    b[sx][sy]=1;                    break;                }        T=99999;//将初始时间设为一个较大的数        dfs(sx,sy,0);        if(T==99999)            puts("Poor ANGEL has to stay in the prison all his life.");        else            printf("%d\n",T);    }    return 0;}

相信代码大家都是能看懂的,加上我的注释,肯定没问题;
希望能给你们一些帮助吧!!!

原创粉丝点击