HDOJ--1242--Rescue

Rescue

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


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

题目大意:给出N和M,N代表行,M代表列,你站在‘r’这个地方 ,问能否到达a处,能的话最少需要多少时间,不能那个的话,输出上面的英文 Poor ANGEL has to stay in the prison all his life.“#”代表墙,“.”代表路,X代表警察,遇到警察,你需要用2分钟时间杀了他。

AC代码:

#include
#include
#include
#define INF 0xfffffff
using namespace std;
int n,m,i,j,ex,ey,ans;
int cx[4]={0,0,1,-1},cy[4]={1,-1,0,0};
char map[210][210];
struct node{
	int x,y,time;
}a,temp;
queueq;
int jud(int x,int y){
	if(x<1||x>n||y<1||y>m)
		return 0;
	if(map[x][y]=='#')
		return 0;
	return 1;
}
void bfs(int x,int y){
	map[x][y]=='#';
	a.x=x;
	a.y=y;
	a.time=0;
	q.push(a);
	while(!q.empty()){
		a=q.front();
		q.pop();
		for(i=0;i<4;i++){
			temp.x=a.x+cx[i];
			temp.y=a.y+cy[i];
				if(map[temp.x][temp.y]=='x')
					temp.time=a.time+2;
				else
					temp.time=a.time+1;
				if(jud(temp.x,temp.y)){
					if(temp.x==ex&&temp.y==ey){
						if(ans>temp.time)
							ans=temp.time;
							continue ;
					}
					map[temp.x][temp.y]='#';
						q.push(temp);	
				}
			
		}
	}
}

int main(){
	int bx,by;
	while(scanf("%d%d",&n,&m)!=EOF){
		ans=INF;
		for(i=1;i<=n;i++){
			getchar();	
			for(j=1;j<=m;j++){
				scanf("%c",&map[i][j]);
				if(map[i][j]=='r'){
					bx=i;
					by=j;
				}
				if(map[i][j]=='a'){
					ex=i;
					ey=j;
				}
			}
		}
			bfs(bx,by);
			if(ans==INF)
				printf("Poor ANGEL has to stay in the prison all his life.\n");
			else
				printf("%d\n",ans);	
	}
	return 0;
}


你可能感兴趣的:(BFS和DFS(搜索类问题))