HDU 1242 Rescue

来源:互联网 发布:ug轮廓3d倒角编程技巧 编辑:程序博客网 时间:2024/04/30 12:33

Rescue

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 22768    Accepted Submission(s): 8045


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."
 

Sample Input
7 8#.#####.#.a#..r.#..#x.....#..#.##...##...#..............
 

Sample Output
13


分析:这个题的示例没有什么代表性,刚开始写出一个DFS直接就过了示例,然后就WA了。该题目‘a’的数目只有一个,是固定的,而‘r’的数目可能会有多个,所以应该从a深搜到r。而且,对于这种字符迷宫题目,个人感觉把路变成墙来改变走过的路,不如设置一个数组标记是否走过,因迷宫中状态量太多,不好还原。

代码如下:

#include <stdio.h>#include <string.h>int n,m;int min_t;char map[205][205];int visited[205][205];int dir[2][4]={{-1,0,1,0},{0,1,0,-1}};void dfs(int i,int j,int time){if(time>=min_t)return ;if(visited[i][j] || i<1 || j<1 || i>n || j>m)return ;if(map[i][j]=='r'){time++;if(time<min_t)min_t=time;return;}else if(map[i][j]=='x')time+=2;elsetime+=1;visited[i][j]=1;for(int k=0;k<4;k++)dfs(i+dir[0][k],j+dir[1][k],time);visited[i][j]=0;}int main(){int star_x,star_y;int i,j;while(~scanf("%d %d",&n,&m)){memset(visited,0,sizeof(visited));for(i=1;i<=n;i++){getchar();for(j=1;j<=m;j++){scanf("%c",map[i]+j);if(map[i][j]=='a'){star_x=i;star_y=j;}if(map[i][j]=='#')visited[i][j]=1;}}min_t=40005;for(int k=0;k<4;k++)dfs(star_x+dir[0][k],star_y+dir[1][k],0);if(min_t==40005)printf("Poor ANGEL has to stay in the prison all his life.\n");elseprintf("%d\n",min_t);}return 0;}



0 0
原创粉丝点击