且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

找到两个给定节点之间的路径?

更新时间:2023-02-01 22:28:25

广度优先搜索 遍历一个图,实际上从一个起始节点找到所有路径.但是,通常 BFS 不会保留所有路径.相反,它更新前驱函数 π 以保存最短路径.您可以轻松修改算法,以便 π(n) 不仅存储 一个 前驱,还存储可能的前驱列表.

Breadth-first search traverses a graph and in fact finds all paths from a starting node. Usually, BFS doesn't keep all paths, however. Instead, it updates a prededecessor function π to save the shortest path. You can easily modify the algorithm so that π(n) doesn't only store one predecessor but a list of possible predecessors.

然后所有可能的路径都在这个函数中编码,通过递归遍历π,你得到所有可能的路径组合.

Then all possible paths are encoded in this function, and by traversing π recursively you get all possible path combinations.

在 Cormen 等人的算法简介 中可以找到使用这种符号的一个很好的伪代码. 随后在许多大学脚本中使用了该主题.在 Google 上搜索BFS 伪代码前身 π"后Stack Exchange 上的这个热门.

One good pseudocode which uses this notation can be found in Introduction to Algorithms by Cormen et al. and has subsequently been used in many University scripts on the subject. A Google search for "BFS pseudocode predecessor π" uproots this hit on Stack Exchange.