写在前面:
广搜和深搜在算法入门中算难的一类,处理的问题的数量级也比较小,但仍是非常重要的算法思想。因为对于要用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?