bsf dfs 专题(一)

本文探讨了深度优先搜索(DFS)和广度优先搜索(BFS)这两种算法,强调了它们在算法入门中的重要性。尽管它们处理的问题规模较小,但掌握这两种算法的基本模板对于解决相关问题至关重要。文章通过实例介绍了BFS,包括一维、二维和三维的应用,并提供了相关题目及解决方案,帮助读者理解和应用这两种搜索方法。
摘要由CSDN通过智能技术生成

 

写在前面:

        广搜和深搜在算法入门中算难的一类,处理的问题的数量级也比较小,但仍是非常重要的算法思想。因为对于要用bfs和dfs解决的题,你如果不会基本模板,暴力也很难写出来,可以说白白丢到的题。所以即使bfs和dfs有一定的学习门槛,但我们仍要跨过,去了解掌握。

      bfs:

       通过这个专题的练习,我个人感觉广搜比深搜简单,广搜可谓万变不离其宗,同一个队列同一个世界,只要学会用队列实现广搜的方法,一维,二维还是三维,差别不大。

基本模板:

void bfs(node x)
{
	queue<node>q;//队列
	q.push(x);//将起点压入
	node t, nx;
	while (!q.empty())
	{
		t = q.front();//从队列取出一个符合条件的点
		q.pop();
		if (t.z == ch - 1 && t.x == n - 1 && t.y == m - 1 && t.time <= k)//判断是否为终点

		{
			flag = 0;
			cout << t.time << endl;
		}
		for (int i = 0; i<6; i++)//如果不是要求的终点,向下一层扩散
		{
			nx.x = t.x + dirstion[i][0];
			nx.y = t.y + dirstion[i][1];
			nx.z = t.z + dirstion[i][2];
			if (nx.x >= 0 && nx.x<n&&nx.y >= 0 && nx.y<m&&nx.z >= 0 && nx.z<ch&&mapp[nx.z][nx.x][nx.y] == 0)
                 //判断新的点是否越界,是否走过和是否为可以走的点
			{
				mapp[nx.z][nx.x][nx.y] = 1;//标记为走过
				nx.time = t.time + 1;//步数加一
				q.push(nx);//压入队列
			}
		}
	}

}

 对此还要掌握队列的基本用法 :https://blog.csdn.net/u011499425/article/details/52576083

相关例题:

一维的BFS

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 20632    Accepted Submission(s): 6014


 

Problem Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值