我试图在定义为的加权图中获得最短路径
import networkx as nx
import matplotlib.pyplot as plt
g = nx.Graph()
g.add_edge(131,673,weight=673)
g.add_edge(131,201,weight=201)
g.add_edge(673,96,weight=96)
g.add_edge(201,96,weight=96)
nx.draw(g,with_labels=True,with_weight=True)
plt.show()
为此我使用
nx.shortest_path(g,source=131,target=96)
预期的答案是 131,201,96,因为对于该路径,我的权重总和最小。我得到的是 131,673,96。我尝试改变重量但是shortest_path
总是返回longest显然是路径。到底是怎么回事?
来自nx.shortest_path 的文档 https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html#networkx.algorithms.shortest_paths.generic.shortest_path:
shortest_path(G, source=None, target=None, weight=None, method='dijkstra')[source]
Compute shortest paths in the graph.
Parameters
G (NetworkX graph)
source (node, optional) – Starting node for path. If not specified, compute shortest paths for each possible starting node.
target (node, optional) – Ending node for path. If not specified, compute shortest paths to all possible nodes.
> 重量(无或字符串,可选(默认 = 无)) – 如果无,则每条边都有权重/距离/成本 1。如果是字符串,则使用此边
属性作为边权重。任何不存在的边缘属性默认值
至 1。
method (string, optional (default = ‘dijkstra’)) – The algorithm to use to compute the path. Supported options: ‘dijkstra’,
(强调我的)
如果您没有明确声明您想要找到最短加权路径(通过指定weight
参数),所有权重都被视为一。
要解决您的问题,请执行以下操作:
print(nx.shortest_path(g,source=131,target=96, weight='weight'))
output:
[131, 201, 96]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)