利用队列实现BFS(广度优先搜索) 您所在的位置:网站首页 广度优先搜索的数据结构 利用队列实现BFS(广度优先搜索)

利用队列实现BFS(广度优先搜索)

2023-12-07 09:51| 来源: 网络整理| 查看: 265

上图: 在这里插入图片描述 对于上图的结构,通过广度优先搜索BFS找到两个节点Node之间的最近距离(比如A和G之间是2)

1. 结点的处理顺序是什么?

在第一轮中,我们处理根结点。在第二轮中,我们处理根结点旁边的结点;在第三轮中,我们处理距根结点两步的结点;。。。。。。。

与树的层序遍历类似,越是接近根结点的结点将越早地遍历。

如果在第 k 轮中将结点 X 添加到队列中,则根结点与 X 之间的最短路径的长度恰好是 k。也就是说,第一次找到目标结点时,你已经处于最短路径中。

2. 队列的入队和出队顺序是什么?

我们首先将根结点排入队列。然后在每一轮中,我们逐个处理已经在队列中的结点,并将所有邻居添加到队列中。值得注意的是,新添加的节点不会立即遍历,而是在下一轮中处理。

结点的处理顺序与它们添加到队列的顺序是完全相同的顺序,即先进先出(FIFO)。这就是我们在 BFS 中使用队列的原因。

对应上面的结构我们的队列元素为:

round1:A->ABCD->BCD (添加根节点-》如果根节点不是目标-》添加根节点的所有子节点) round2:BCD->BCDE->CDE->CDEF->DEF->DEFG->EFG(判断B是不是,不是则添加B的所有子节点,并将B出队;判断C是不是,如果C不是则添加C的所有子节点入队,并将C出队…略) round3:EFG->FG->G(判断E是不是,E不是添加E的所有子节点,判断F是不是。。。。。。。)

伪代码 /** * Return the length of the shortest path between root and target node. */ int BFS(Node root, Node target) { Queue queue; // store all nodes which are waiting to be processed int step = 0; // number of steps neeeded from root to current node // initialize add root to queue; // BFS while (queue is not empty) { step = step + 1; // iterate the nodes which are already in the queue int size = queue.size(); for (int i = 0; i add next to queue; } remove the first node from queue; } } return -1; // there is no path from root to target } 确保不会重复添加子节点的伪代码:

其中添加了Set,用来去重;

/** * Return the length of the shortest path between root and target node. */ int BFS(Node root, Node target) { Queue queue; // store all nodes which are waiting to be processed Set used; // store all the used nodes int step = 0; // number of steps neeeded from root to current node // initialize add root to queue; add root to used; // BFS while (queue is not empty) { step = step + 1; // iterate the nodes which are already in the queue int size = queue.size(); for (int i = 0; i if (next is not in used) { add next to queue; add next to used; } } remove the first node from queue; } } return -1; // there is no path from root to target }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有