HDU - 1242 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

题目大意:帮助天使a的朋友r找到天使,注意一个小坑:朋友可能有多个。故以a为起点坐标,分三种情况,墙为‘#’,警卫为‘x’,警卫耗时为2,‘.’为道路,利用深搜算法进行回溯递归。

#include 
#include
#include 
using namespace std;
char map[250][250];
int curstep;
int minstep;
int vis[250][250];
int x,y,m,n;
int dir[4][2]={0,1,0,-1,-1,0,1,0};
void dfs(){
    if(map[x][y]=='r' ) {
        if(curstepreturn;
    }
    for(int d=0;d<4;d++){
        if(curstep>=minstep)  continue;
        x=x+dir[d][0];
        y=y+dir[d][1];
        if(vis[x][y]!=1 && map[x][y]!='#' && x>=0 && x=0 && yif(map[x][y]=='x') {
                vis[x][y]=1;
                curstep+=2;
                dfs();
                curstep-=2;
                vis[x][y]=0;
            }
            if(map[x][y]=='r' || map[x][y]=='.'){
                vis[x][y]=1;
                curstep++;
                dfs();
                curstep--;
                vis[x][y]=0;
            }
        }
        x=x-dir[d][0];
        y=y-dir[d][1];
    }   
}
#define INFINITE 0x7fffffff
int main(){

while(scanf("%d %d",&m,&n)!=EOF){
    memset(vis,0,sizeof(vis));  
    minstep=INFINITE;
    curstep=0;
    for(int i=0;ifor(int j=0;jcin>>map[i][j];
        if(map[i][j]=='a'){
            x=i;y=j;
        }
    }
} 
vis[x][y]=1;
dfs();
if(minstep==INFINITE) printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n",minstep);
}

}

你可能感兴趣的:(ACM)