【问题标题】:How to get the shortest path in a weighted graph with NetworkX?如何使用 NetworkX 获得加权图中的最短路径?
【发布时间】:2020-04-08 03:17:15
【问题描述】:

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

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 路径。怎么回事?

【问题讨论】:

  • 131, 673, 96 它正是最短路径。除非你改变你的体重
  • @Camue 但是 131,673,96 的总和大于 131,201,96 那么它怎么可能是最短路径呢?关于权重的工作原理,我有什么需要了解的吗?两个节点之间的权重越大,它们之间的距离就越远是对的?

标签: python graph networkx shortest-path


【解决方案1】:

来自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’,

(强调我的)

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

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

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

输出:

[131, 201, 96]

【讨论】:

  • “weight='weight'”对我有用。感谢您分享您的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多