您的位置:首页 > 产品设计 > UI/UE

搜索2(广度优先)Rescue

2017-05-04 21:03 344 查看

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)


Total Submission(s) : 20   Accepted Submission(s) : 10


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:在定义结构体是多了  friend bool operator<(node a,node b)  判断升降序输出
3:与基础队列取对手元素是是q.top了
 

下面是这题的代码:
#include<iostream>
#include<string>
#include<string.h>
#include<sstream>
#include<queue>
using namespace std;
struct node
{
int x,y,time;
friend bool operator<(node a,node b)
{
return a.time>b.time;  //先输出小的
}
}s;
int n,m;
char a[205][205];  。//地图
int dir[4][2]={{1,0},{0,1},{0,-1},{-1,0}};//走的方向
void bfs()
{
priority_queue<node>q;
node t,x1;
q.push(s);  //从起始点开始
while (!q.empty())
{
t=q.top();
q.pop();
for (int i=0;i<4;i++)
{
x1.y=t.y+dir[i][1];
x1.x=t.x+dir[i][0];
if(x1.x>=0&&x1.x<n&&x1.y>=0&&x1.y<m&&a[x1.x][x1.y]!='#')
{
x1.time=t.time+1;
if (a[x1.x][x1.y]=='x')  //碰到守卫多加时间
x1.time++;
else if (a[x1.x][x1.y]=='a')
{
cout<<x1.time<<endl;
return;
}
a[x1.x][x1.y]='#';
q.push(x1);
}
}
}
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;  //无法到达
}
int main()
{
int i,j;
while (cin>>n>>m)  //输入地图寻找起点
{
for (i=0;i<n;i++)
for (j=0;j<m;j++)
{
cin>>a[i][j];
if (a[i][j]=='r')
{
s.x=i;
s.y=j;
s.time=0;
}
}
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  广度优先 搜索