Rescue

来源:互联网 发布:淘宝首页设计一套多钱 编辑:程序博客网 时间:2024/05/22 07:58

Rescue

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


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的方格中,'#/是墙不可过,'.'是路可过,a代表要救出的    公主,r是出发的friend,x代表守卫,每走一步都需要一单位    的时间,遇到守卫需要额外再消耗一单位的时间,求从r走到a    最短需多少的时间。     要注意从a开始搜索,因为r可能含有多个。 */
#include<stdio.h>#include<string.h>#include<queue>#include<iostream>using namespace std;#define N 210struct node{ int x,y,ans; friend bool operator<(node x,node y) {  return x.ans>y.ans;//重载<,排序,时间小的优先级高放队首。  }};char a[N][N];int n,m,ax,ay;int dx[4]={0,1,-1,0};int dy[4]={1,0,0,-1};int b[N][N];void bfs(int x,int y){ memset(b,0,sizeof(b)); priority_queue<node>q; node f1,f2; f1.x=x; f1.y=y; f1.ans=0; q.push(f1); b[x][y]=1; while(!q.empty()) {  f1=q.top();  q.pop();  if(a[f1.x][f1.y]=='r')  {   printf("%d\n",f1.ans);   return ;  }  for(int i=0;i<4;i++)  {   f2.x=f1.x+dx[i];   f2.y=f1.y+dy[i];   if(f2.x>0&&f2.x<=n&&f2.y>0&&f2.y<=m&&!b[f2.x][f2.y]&&a[f2.x][f2.y]!='#')   {    b[f2.x][f2.y]=1;//搜过的路要做标记,这一点和dfs不同,dfs是   标记->dfs->取消标记    if(a[f2.x][f2.y]=='x')    {     f2.ans=f1.ans+2;    }    else     f2.ans=f1.ans+1;    q.push(f2);    }  } } printf("Poor ANGEL has to stay in the prison all his life.\n");}int main(){ int i,j; while(scanf("%d%d",&n,&m)!=EOF) {  for(i=1;i<=n;i++)   scanf("%s",a[i]+1);  for(i=1;i<=n;i++)  {   for(j=1;j<=m;j++)   {    if(a[i][j]=='a')    {     ax=i;     ay=j;    }   }  }  bfs(ax,ay); } return 0;}

搜索
0 0
原创粉丝点击