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

hdu 1242 Rescue(优先队列 && 广搜BFS)

2016-12-09 16:52 525 查看
[align=center] Rescue[/align]
[align=left]原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242[/align]
[align=left]题意:Angel被关押在牢里,Angel的朋友要去救Angel,给出Angel的朋友的位置(起点),求到达Angel的位置(终点)最小需要用多少时间。(路上遇见守卫,打败守卫需要花费1m)[/align]
[align=left]思路:用BFS来搜索最短时间,注意 可能遇见守卫所以需要用到优先队列,让时间短的先出队。[/align]
另外特别注意可能有多个'r',因此可以让终点为起点,找到时间最短的'r'。(然而 题目的后台数据可能只有一个r


[align=left]代码:[/align]
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
char a[202][202];
bool vis[202][202];
int to[4][2]= {0,1,0,-1,1,0,-1,0};//方向
int n,m;
struct node
{
int x,y,s;
friend bool operator < (node a,node b)//重载运算符,使时间小的先出队
{
return a.s>b.s;
}
};
int bfs(int x,int y)
{
node now,next;
priority_queue<node>w;
now.x=x,now.y=y,now.s=0;//将起点放入队列
w.push(now);
vis[x][y]=1;
while(!w.empty())
{
now=w.top();//取出队列的头
if(a[now.x][now.y]=='r')//找到终点
return now.s;
w.pop();
for(int i=0; i<4; i++)
{
int cnt=now.x+to[i][0],ans=now.y+to[i][1];
if(cnt>=0&&ans>=0&&cnt<n&&ans<m&&a[cnt][ans]!='#'&&!vis[cnt][ans])
{
vis[cnt][ans]=1;
next.x=cnt,next.y=ans,next.s=now.s+1;
if(a[cnt][ans]=='x')
next.s++;
w.push(next);
}
}
}
return 0;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(vis,0,sizeof(vis));
int i,j,x,y;
for(i=0; i<n; i++)
{
scanf("%s",&a[i]);
for(j=0; j<m; j++)
if(a[i][j]=='a')//找到起点
x=i,y=j;
}
int k=bfs(x,y);
if(k)
printf("%d\n",k);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: