当前位置: 代码迷 >> 综合 >> Rescue (bfs广度优先搜索)
  详细解决方案

Rescue (bfs广度优先搜索)

热度:78   发布时间:2024-01-31 19:17:03.0

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

题目翻译

题目的意思是你是天使的朋友现在要救天使,#为墙 .为路 r为出发点,a为天使位置,x为敌人
每走过一个.花费1s,走过一个x花费2s问你最快救出天使的时间,如果救不出来就输出"Poor ANGEL has to stay in the prison all his life."

题目分析

地图搜索使用广度搜索的模板题,只需要变一下型加入优先队列priority_queue直接排序输出就可以了,上代码

代码实现

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<map>
#include<set> 
#include<string>
#include<stack>
#include<math.h>
#include<queue>
using namespace std;
/* 输入N M分别代表行数和列数 拯救天使,a为天使位置,r为起始位置 .为一秒可通过路径 x为敌人多一秒时间 #为不可通过路径 */
struct node{int x;int y;int step;friend bool operator < (node a,node b) { return a.step>b.step;}
};
char a[210][210];
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int n,m;
node x;
bool pd(int x,int y)//来判断当前位置是否越界或为墙 
{if(x>=0&&x<n&&y>=0&&y<m&&a[x][y]!='#')return true;elsereturn false;} 
int dfs()
{priority_queue<node> q;q.push(x);//点入队node now,next;while(!q.empty()){now=q.top();//优先队列是top,普通队列是frontq.pop();for(int i=0;i<4;i++){next.x=now.x+dir[i][0];next.y=now.y+dir[i][1];if(a[next.x][next.y]=='a')return next.step;if(pd(next.x,next.y)) {if(a[next.x][next.y]=='.'){next.step=now.step+1;}if(a[next.x][next.y]=='x'){next.step=now.step+2;}q.push(next);//成立就将这个点入队 a[now.x][now.y]='#';//将此处定义为墙,相当于标记走过 }}} return 0;
}
int main()
{int flag=0;//来判断输出 while(cin>>n>>m){for(int i=0;i<n;i++){for(int j=0;j<m;j++){cin>>a[i][j];if(a[i][j]=='r'){x.x=i;x.y=j;x.step=0;}}}flag=dfs(); if(flag){printf("%d\n",flag);}else{printf("Poor ANGEL has to stay in the prison all his life.\n");}}return 0;
}