HDU-1242-Rescue

HDU-1242-Rescue

http://acm.hdu.edu.cn/showproblem.php?pid=1242

bfs即可,可能有多个’r’,而’a’只有一个,从’a’开始搜,找到的第一个’r’即为所求

需要注意的是这题宽搜时存在障碍物,遇到’x’点是,时间+2,如果用普通的队列就并不能保证每次出队的是时间最小的元素,所以要用优先队列,第一次用优先队列,还不熟练哇

优先队列(priority_queue)的基本操作:

empty();队列为空返回1

pop();出队

push();入队

top();返回队列中优先级最高的元素

size();返回队列中元素的个数

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;
char map[205][205];
int visit[205][205];
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int n,m;
struct node
{
	int x,y;
	int time;
	friend bool operator < (const node &a,const node &b)  //时间小的先出队
	{
		return a.time>b.time;
	}
};
int go(int x,int y)
{
	if(0<=x&&x<n&&0<=y&&y<m&&map[x][y]!='#')
    return 1;
	return 0;
}
int bfs(int x,int y)
{
	int i;
	node st,ed;
	priority_queue<node>que;  //定义一个优先队列
	memset(visit,0,sizeof(visit));
    st.x=x;
	st.y=y;
	st.time=0;
	visit[st.x][st.y]=1;
	que.push(st);
	while(!que.empty())
	{
		st=que.top();
		que.pop();
		if(map[st.x][st.y]=='r')
		return st.time;
        for(i=0;i<4;i++)
		{
			ed.x=st.x+dir[i][0];
			ed.y=st.y+dir[i][1];
			if(go(ed.x,ed.y)&&!visit[ed.x][ed.y])
			{
				visit[ed.x][ed.y]=1;
				if(map[ed.x][ed.y]=='x')
				ed.time=st.time+2;
				else
				ed.time=st.time+1;
				que.push(ed);
			}
		}
	}
	return -1;
}
int main()
{
	int i,j;
	int x,y,ans;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(i=0;i<n;i++)
		scanf("%s",map[i]);
		for(i=0;i<n;i++)
		for(j=0;j<m;j++)
		if(map[i][j]=='a')
		{
			x=i;
			y=j;
			break;
		}
		ans=bfs(x,y);
		if(ans==-1)
		printf("Poor ANGEL has to stay in the prison all his life.\n");
		else
		printf("%d\n",ans);
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值