我正在尝试找到所有可能的最短路径
这是我的代码:
import networkx as nx
g=nx.Graph()
e=[('a', 'b', 2), ('a', 'c', 6), ('b', 'c', 4), ('c', 'e', 5), ('c', 'f', 1)]
paths=nx.shortest_paths(g,'a','c',weight=True)
print('%s' %list(paths))
这是输出:
[['a', 'c']]
根据权重,a-> b-> c也是最短的路径。
为什么不输出?
最佳答案
我无法在笔记本电脑上运行您的代码。
networkx-1.11
Python 2.7.13
所以我尝试使用
all_shortest_paths
方法,也许在某种程度上它们是相似的。这是我的代码:import networkx as nx
G = nx.Graph()
e = [('a', 'b', 2), ('a', 'c', 6), ('b', 'c', 4)]
for i in e:
G.add_edge(i[1], i[0], weight=i[2])
paths = nx.all_shortest_paths(G, source='a', target='c',weight=True)
print list(paths)
我得到了相同的输出,并且阅读了有关all_shortest_paths的networkx文档:
重量
(无或字符串,可选(默认=无))–如果为无,则每
边具有权重/距离/成本1.如果是字符串,请使用此边属性
作为边缘重量。任何不存在的edge属性默认为1。
所以我想
weight=True
是无效的,所以任何不存在的edge属性默认为1,这就是为什么无法获得所需结果的原因。如果您修改代码并将
weight=True
更改为weight='weight'
。你会得到:
[['a', 'c'], ['a', 'b', 'c']]
希望这可以帮助。