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

时间:2015-04-08 10:34:27

标签: python igraph

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

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

2 个答案:

答案 0 :(得分:4)

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

自迭代以来,代码的时间成本应为g.get_shortest_pathsO(V^2)的费用。

对于您的案例中的所有对最短路径问题,建议Floyd–Warshall algorithm使用动态编程来达到O(V^3)

的时间成本

<强>编辑:

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

答案 1 :(得分:1)

前段时间我在python中为给定的图实现了未经优化的Dijkstra's algorithm

def define_undirected_G(): 
   m = 10 #nodes
   G = [set() for _ in range(m)]  #create a set for each node 
                                  #and save the adjacent nodes inside these sets 
   G[0] |= {1,2}
   G[1] |= {0,2,3,4}
   G[2] |= {0,1,4,6,7}
   G[3] |= {1,4}
   G[4] |= {1,2,3,5}
   G[5] |= {4}
return G

def dijkstra(G,s): 
       m = len(G) 
       d = [None]*m  #Shortest paths from s to all nodes in G
       d[s] = 0      #Path cost=0 for the startnode
       Q = {u for u in range(m)}   #Q = All nodes u in G
       while Q: # Selection of node with min d-value
           (_,v) = min({(d[u],u) for u in Q if d[u]!= None})
           Q.remove(v) 
           for u in G[v]: #Check Update for all adjacent nodes
               alt = d[v] + G[v][u]   #Greedy-selection-rule            
               if d[u]==None or alt < d[u]:   #Update
                   d[u] = alt 
       return d 

如果你想让一个S包含G中所有节点的所有最佳路径,那么只需计算G中s的dijkstra(G,s)并将结果加到S中。

注意:优化将是 联盟查找数据结构 ,并在G [v] >因为没有必要检查已经更新过的相邻节点并从未触及的节点集Q中删除,因为贪婪的algrotihms是贪婪的。

希望这有帮助。