计算G中任意两个顶点u,v之间的最短路径

编程入门 行业动态 更新时间:2024-10-10 04:20:10
本文介绍了计算G中任意两个顶点u,v之间的最短路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想找到在图中任意两个顶点之间包含最短路径的集合S. 以下代码可以正常工作,但是我不确定是否有更高效的代码具有相同的功能.

I want to find the set S that contains the shortest path between any two vertices in a graph. The following code is working fine, but I am not sure if there is a more efficient code that does the same functionality.

def getShortestPaths(g): shortestPaths = [] #iterate all pair of nodes for x in itertoolsbinations(g.vs["label"], 2): path = len(g.get_shortest_paths(v=x[0],to=x[1])[0]) - 1 shortestPaths.append(path) return shortestPaths

推荐答案

当前代码的效率取决于g.get_shortest_paths的实现.通常,g.get_shortest_paths的选择包括:

The efficiency of your current code depends on the implementation of g.get_shortest_paths. Typically choices of g.get_shortest_paths include:

  • Bellman-Ford算法,该算法应在O(VE)上运行,
  • Dijkstra的算法,该算法无需优化即可在O(V^2)上运行,O(Elog(v))甚至优化后的O(E+Vlog(E/V)log(V)).
  • Bellman–Ford algorithm, which shall run at O(VE),
  • Dijkstra's algorithm, which shall run at O(V^2) without optimization, O(Elog(v)) or even O(E+Vlog(E/V)log(V)) if well-optimized.

自迭代以来,代码的时间成本应为g.get_shortest_paths乘O(V^2)的成本.

And the time cost of your code shall be the cost of g.get_shortest_paths times O(V^2) since the iteration.

对于您所遇到的所有对最短路径问题,弗洛伊德–沃舍尔建议使用算法,该算法使用动态编程来达到O(V^3)

For all-pairs-shortest-path problem in your case, Floyd–Warshall algorithm is suggested which uses dynamic programming to reach a time cost of O(V^3)

已编辑

上面使用的符号:E表示边的数量,V表示图形中的顶点数量.

Notations used above: E for number of edges, and V for number of vertices in the graph.

更多推荐

计算G中任意两个顶点u,v之间的最短路径

本文发布于:2023-11-30 15:10:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650458.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最短   顶点   路径   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!