networkx不给出加权图的所有最短路径

2024-04-25 23:08:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找所有可能的最短路径

这是我的代码:

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))

输出如下:

^{pr2}$

根据权重,a->;b->;c也是最短路径。在

为什么它没有投入产出?在


Tags: 代码importgt路径networkxtrueaslist
2条回答

我不能在我的笔记本上运行你的代码。在

networkx-1.11
Python 2.7.13

所以我尝试使用all_shortest_paths方法,也许在某种程度上他们类似的。这里我的代码是:

^{pr2}$

我得到了相同的输出,我阅读了networkx文档关于all_shortest_paths

  • 重量

    (None or string, optional (default = None)) – If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1.

所以我假设weight=True是无效的,所以任何不存在的edge属性都默认为1,这就是为什么你不能得到你想要的结果。在

如果修改代码并将weight=True更改为weight='weight'。在

您将获得:

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

希望这有帮助。在

使用all_shortest_paths函数代替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')])

输出:

^{pr2}$

相关问题 更多 >