如何使用 NetworkX 在加权图中获得最短路径?

abh*_*hay 3 python graph shortest-path networkx

我试图在定义为的加权图中获得最短路径

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()
Run Code Online (Sandbox Code Playgroud)

这样做我使用

nx.shortest_path(g,source=131,target=96)
Run Code Online (Sandbox Code Playgroud)

预期的答案是 131,201,96,因为对于该路径,我的权重总和最少。我得到的是 131,673,96。我尝试改变权重,但显然shortest_path总是返回最长的路径。到底是怎么回事?

war*_*ped 9

来自nx.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. 
Run Code Online (Sandbox Code Playgroud)

> weight (None or string, optional (default = None)) – 如果没有,每条边的权重/距离/成本为 1。如果是字符串,使用这个边属性作为边权重。任何不存在的边属性默认为 1。

method (string, optional (default = ‘dijkstra’)) – The algorithm to use to compute the path. Supported options: ‘dijkstra’,
Run Code Online (Sandbox Code Playgroud)

(强调我的)

如果您没有明确声明要找到最短的加权路径(通过指定weight参数),则所有权重都被视为一。

要解决您的问题,请执行以下操作:

print(nx.shortest_path(g,source=131,target=96, weight='weight'))
Run Code Online (Sandbox Code Playgroud)

输出:

[131, 201, 96]
Run Code Online (Sandbox Code Playgroud)