networkx没有为加权图提供所有最短路径

时间:2017-03-12 07:49:33

标签: python networkx

我想找到所有可能的最短路径

这是我的代码:

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也是最短路径

为什么不输入?

2 个答案:

答案 0 :(得分:1)

而不是shortest_paths使用all_shortest_paths功能。

请尝试以下代码:

import networkx as nx
g=nx.Graph()
g.add_edge('a','b', distance=2)
g.add_edge('a','c', distance=6)
g.add_edge('b','c', distance=4)
g.add_edge('c','e', distance=5)
g.add_edge('c','f', distance=1)
print([p for p in nx.all_shortest_paths(g,source='a',target='c',weight='distance')])

输出:

[['a', 'c'], ['a', 'b', 'c']]

答案 1 :(得分:0)

我无法在笔记本电脑上运行您的代码。

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的网络x文档:

  • 重量
      

    无或字符串,可选(默认=无)) - 如果为None,则为每个   edge有权重/距离/成本1.如果是字符串,请使用此edge属性   作为边缘重量。任何不存在的边缘属性默认为1

所以我认为weight=True无效,因此任何不存在的边缘属性默认为1 ,这就是您无法获得所需结果的原因。

如果您修改了代码并将weight=True更改为weight='weight'

你会得到:

[['a', 'c'], ['a', 'b', 'c']]

希望这有帮助。

相关问题