Rescue(广度优先搜索)

来源:互联网 发布:淘宝号升3心方法 编辑:程序博客网 时间:2024/06/08 02:30

Rescue

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
深搜超时,广搜可以;

这一此我们介绍广度优先搜索

按照惯例,我们还是先说一下该题目的主要易错点

1.天使可能有多个朋友,所以不能从朋友的位置开始着天使,只能是从天使找离他最近的朋友

2.题目要求的是找到一个用时最少的朋友,而不是步数最少

既然是广度优先,那么必然用到队列,但是队列只能是先进先出,即是步数少的先遍历到,显然是不符合题目要求的,那应该怎么办呢?

c++给我们提供了标准的函数库,可以引入#include <queue> 并定义优先队列类型 priority_queue,并自动对里面的元素进行排序

如果排序不符合要求,可以给出小于号 “<” 的运算符重载函数,当然在结构体里面进行了,代码里面有具体的实现

广度优先搜索依然是简单的 出队--》判断--》扫描---》入队 的四部曲。结构简单,程序也容易实现,现直接给出代码实现

#include<stdio.h>#include<queue>#include<string.h>using namespace std;char map[202][202];int vis[202][202];int n,m;int mov[4][2]={{1,0},{-1,0},{0,1},{0,-1}};//不能用move好像,move编译错误;struct node{int x,y;int time;friend bool operator<(node a,node b){return a.time>b.time;}};void bfs(int a,int b){    node now,next;priority_queue<node>p;memset(vis,0,sizeof(vis));now.x=a;now.y=b;now.time=0;p.push(now);vis[a][b]=1;while(!p.empty()){now=p.top();p.pop();for(int i=0;i<4;i++){next.x=now.x+mov[i][0];next.y=now.y+mov[i][1];if(next.x>=1&&next.x<=n&&next.y>=1&&next.y<=m&&map[next.x][next.y]!='#'&&vis[next.x][next.y]!=1){vis[now.x][now.y]=1;if(map[next.x][next.y]=='r'){printf("%d\n",now.time+1);return;}if(map[next.x][next.y]=='.')next.time=now.time+1;else if(map[next.x][next.y]=='x')next.time=now.time+2;p.push(next);}}}printf("Poor ANGEL has to stay in the prison all his life.\n");}int main(){while(~scanf("%d %d",&n,&m)){int i,j;int start1=0,start2=0;for(i=1;i<=n;i++){getchar();for(j=1;j<=m;j++){scanf("%c",&map[i][j]);if(map[i][j]=='a'){start1=i;start2=j;}}}bfs(start1,start2);}return 0;}




0 0
原创粉丝点击