All shortest paths for weighted graphs with networkx?

落爺英雄遲暮 提交于 2019-12-11 01:14:38

问题


I have a graph composed by two different sets of edges. The first set is made by edges of weight 1 (list 1). The second set is made by edges of weight 2 (list 2). First, I create the graph with networkx and then use add_edges_from to add list 1 and list 2. I would like to compute all the shortest paths in this weighted graph. Basically I'm looking for the analogous of "all_shortest_paths" but with weights (looks like "dijkstra" module does not allow you to know all the possible routes between a given source and a given target). If I try to use "all_shortest_path" with weighted links (3-tuples, the two nodes and the weight) I get the error . Can anybody help me? Thanks a lot!


回答1:


Here is a simple example to show how all_shortest_paths() works

import networkx as nx
import StringIO
edges = StringIO.StringIO("""
a b 1
a bb 1
b c 2
bb c 2
c d 1
a d 10""")
G = nx.read_weighted_edgelist(edges, nodetype=str)
print list(nx.all_shortest_paths(G, 'a', 'd', weight='weight'))
# [['a', 'b', 'c', 'd'], ['a', 'bb', 'c', 'd']]


来源:https://stackoverflow.com/questions/16550292/all-shortest-paths-for-weighted-graphs-with-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!