如何在networkX中获得最短路径

时间:2019-12-15 11:25:29

标签: python graph networkx

这里的ans应该是131,201,96,因为总和最少,但是我得到了131,673,96,这与我尝试更改权重值完全相反,但是最短路径总是返回最长路径? 任何帮助将不胜感激。谢谢

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)
print(nx.shortest_path(g,source=131,target=96))
plt.show()

1 个答案:

答案 0 :(得分:3)

来自documentation of 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. 
     

>体重   (无或字符串,可选(默认=无))–如果为无,则每个边缘的权重/距离/成本为1。如果为字符串,则使用此边缘       属性作为边缘权重。任何不存在的边属性默认       到1。

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

(重点是我的)

如果未明确指出要找到最短的加权路径(通过指定weight参数),则所有权重均视为1。

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

print(nx.shortest_path(g,source=131,target=96, weight='weight'))

输出:

[131, 201, 96]