HDOJ-1242-RESCURE(营救公主)【BFS+优先队列】

本文深入解析BFS算法在解决“救援公主”问题中的应用,通过实例演示了优先队列与广搜的基本操作,以及如何利用算法进行路径搜索与优化。详细讲解了代码实现过程,包括数据结构设计、边界条件处理与状态转移逻辑,帮助读者理解算法精髓并应用于类似问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* Function Description:   HDOJ 1242  
   Environment:        DEV C++ 5.6.3.1
   Technique:		
   Version:
   Author:                 valar morghulis
   Date:                   20150806
   Notes:正难则反,只有一个公主,但有好多‘男人’来救她。。。 
        不但用到优先队列,还是经典的广搜题,BFS经典题目哦 
 	可以看出来题中输入数据的x代表守卫,#代表墙,a是美丽的小公主,r是勇士们 
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
*/
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
char map[201][201];//The array (stand for PRISON)
int M,N,direction[4][2]={ {1,0},{-1,0}, {0,1},{0,-1}};
 struct node//dingyi youxianduilie in jiegouti
 {
 	int x;
 	int y;
 	int step;
 	friend bool operator<(node x, node y)//don't forget the '<' hui  error  de!
 	{
 		return x.step > y.step;
 	}
 };
 void bfs(node);
 int main()
 {
 	node start;
 	while(~scanf("%d%d",&N,&M))
 	{
 		for(int i=1;i<=N;i++)
 		{
 			getchar();//absorb the plank
			 for(int j=1;j<=M;j++)
			 {
			 	scanf("%c",&map[i][j]);
			 	if(map[i][j]=='a')
			 	{	
			 		start.x=i;
			 		start.y=j;
			 		start.step=0;
			 	//	
			 	}
			 } 
 		}
 		bfs(start);
 	}
 	return 0;
 }
 void bfs(node x)
 {
	node a,b;
	priority_queue <node> q;//you xian dui lie 
	q.push(x);//first yuansu jin duiwu
 	while(!q.empty())
 	{
 		a=q.top();//top yuansu chudui jie shou zhemo~~
 		q.pop();//at the same time qingkong zhege position leave next yuansu
 		for(int i=0;i<4;i++)//yicentyiceng de xunhuan search zhe jiu shi BFS de character 
 		{
 			b.x=a.x+direction[i][0];//direction up&&down
 			b.y=a.y+direction[i][1];//direction left && right
 			b.step=a.step+1;
 			if(b.x<1||b.y<1||b.x>N||b.y>M||map[b.x][b.y]=='#')
 			continue ;
 			if(map[b.x][b.y]=='x')
 			b.step++;
 			if(map[b.x][b.y]=='r')
 			{
 				printf("%d\n",b.step);
 				return;
 			}
 			map[b.x][b.y]='#';
 			q.push(b);
 		}
 	}
 	printf("Poor ANGEL has to stay in the prison all his life.\n");
 	return ;
 	
 }
 

最近纠结BFS算法几天了,简直不能自拔;RESCURE这道题虽然不是很复杂,可其中的BFS思想还是很经典了,尤其是在for循环那块,你能很清晰的体会到BFS算法的分层循环、由近及远的思想。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值