如何找到覆盖有向循环图中所有节点的最短路径?
我需要一个从一个节点开始的有向循环图的最短路径的示例 (它应该从将成为输入的节点到达图形的所有节点)。
如果有一个例子,我需要 C++ 或算法。
I need an example of the shortest path of a directed cyclic graph from one node
(it should reach to all nodes of the graph from a node that will be the input).
Please if there is an example, I need it in C++, or the algorithm.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:哎呀,误读了问题。 感谢@jfclavette 选择这个。 老答案在最后。
您要解决的问题称为旅行推销员问题。 有很多潜在的解决方案,但它是 NP 完全的,所以你无法解决大图。
旧答案:
您要查找的称为图形的周长。 可以通过将节点到自身的距离设置为无穷大并使用 Floyd-Warshall 算法。 从节点 i 开始的最短循环的长度就是位置 ii 的条目。
EDIT: Oops, misread the question. Thanks @jfclavette for picking this up. Old answer is at the end.
The problem you're trying to solve is called the Travelling salesman problem. There are many potential solutions, but it's NP-complete so you won't be able to solve for large graphs.
Old answer:
What you're trying to find is called the girth of a graph. It can be solved by setting the distances from a node to itself to infinity and using the Floyd-Warshall algorithm. The length of the shortest cycle from node i is then just the entry in position ii.
在未加权的情况下:广度优先搜索。
在加权情况下:Dijkstra's。
In the unweighted case: Breadth first search.
In the weighted case: Dijkstra's.
在伪代码中:
这在每个顶点上运行略有不同的 Dijkstra。 变异的迪克斯特拉
有一些关键的区别。 首先,所有初始距离都设置为 ∞,甚至
起始顶点。 其次,起始顶点必须先放入队列中才能使
确保它首先出现,因为它们都有相同的优先级。 最后,
突变的 Dijkstras 返回到起始节点的距离。 如果没有
返回起始顶点的路径距离仍为 ∞。 所有这些中的最小值
从变异的 Dijkstras 返回是最短路径。 自从迪杰斯特拉斯运行以来
最坏的情况是 O(|V|^2) 且 min_cycle 运行这种形式的 Dijkstras |V| 次,
找到最短循环的最终运行时间是 O(|V|^3)。 如果 min_cyc 返回
∞ 则该图是无环图。
要返回最短循环的实际路径,只需进行少量修改。
In Pseudocode:
This runs a slightly different Dijkstra's on each vertex. The mutated Dijkstras
has a few key differences. First, all initial distances are set to ∞, even the
start vertex. Second, the start vertex must be put on the queue first to make
sure it comes off first since they all have the same priority. Finally, the
mutated Dijkstras returns the distance back to the start node. If there was no
path back to the start vertex the distance remains ∞. The minimum of all these
returns from the mutated Dijkstras is the shortest path. Since Dijkstras runs
at worst in O(|V|^2) and min_cycle runs this form of Dijkstras |V| times, the
final running time to find the shortest cycle is O(|V|^3). If min_cyc returns
∞ then the graph is acyclic.
To return the actual path of the shortest cycle only slight modifications need to be made.
对于非加权图,BFS 将完成这项工作。 由于图中存在潜在的循环,因此您需要跟踪访问的节点(无论如何,您都需要为 BFS 执行此操作)。
对于加权图,可以使用贝尔曼-福特算法。 它还能够检测周期。
For non weighted graph, BFS will do the job. Since there is potential cycle in your graph, you need to keep track of visited node (you sort of need to do this for BFS anyway).
For weighted graph, bellman–Ford algorithm can be used. It is also able to detect cycles.