HDU1242 Rescue(优先队列加BFS)

本文通过一道使用BFS算法从终点逆向寻找起点路径的问题,详细介绍了如何利用优先队列实现这一过程。代码中展示了如何定义结构体节点,设置访问标记,以及遍历地图寻找最优路径的具体步骤。

   这题是一道BFS题目,要从终点逆着推起点,需要用上优先队列。

   点击打开链接

#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
int visit[205][205],s[]={1,-1,0,0},t[]={0,0,1,-1},ss,tt,flag,n,m;
char map[205][205];
struct sb
{
	int step,x,y;
	bool operator<(const sb &t) const
	{
		return step>t.step;
	}
};	
priority_queue<sb>q;
int bfs(int xx,int yy)
{
	int i;
	sb e={0,xx,yy};
	visit[xx][yy]=1;
	q.push(e);
	while(!q.empty())
	{
		e=q.top();
		q.pop();
		for(i=0;i<4;i++)
		{
			ss=e.x+s[i];
			tt=e.y+t[i];
			if(ss>=1&&ss<=n&&tt>=1&&tt<=m)
			{
				if(!visit[ss][tt]&&map[ss][tt]=='.')
				{
					sb e1={e.step+1,ss,tt};
					q.push(e1);
					visit[ss][tt]=1;
				}
				else if(!visit[ss][tt]&&map[ss][tt]=='r')
				{
					flag=1;
					break;
				}
				else if(!visit[ss][tt]&&map[ss][tt]=='x')
				{
					sb e1={e.step+2,ss,tt};
					q.push(e1);
					visit[ss][tt]=1;
				}
			}
		}
		if(flag==1)
			break;
	}
	while(!q.empty())
		q.pop();
	return e.step+1;
}
int main()
{
	int i,j,xx,yy;
	while(cin>>n>>m)
	{
		memset(map,0,sizeof(map));
		memset(visit,0,sizeof(visit));
		flag=0;
		for(i=1;i<=n;i++)
		{
			for(j=1;j<=m;j++)
			{
				cin>>map[i][j];
				if(map[i][j]=='a')
				{
					xx=i;
					yy=j;
				}
			}
		}
		int count=bfs(xx,yy);
		if(flag==1)
			cout<<count<<endl;
		else
			cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值