python - networkx 中具有 'key' 个节点可访问的最短路径

标签 python networkx

我有一个用networkx开发的python G有向图。该图具有称为“权重”的权重。

我知道一个显式的起始节点 A 和一个结束节点 F。在图之间可以访问节点 B、C、D、E。

我怎么能明确地说他必须通过找到最短路径来访问B和D,并且可以另外添加C和E,如果这有助于最短路径?

到目前为止我知道这个功能:

nx.single_source_dijkstra(G, 'A', target='F', cutoff=None, weight='weight')

给出输出:

(10.01,
['A',
 'B',
 'C',
 'F',])

如何确保它包含 E?

最佳答案

Networkx 没有内置函数或参数来解决您的问题。您应该手动执行此操作:

import networkx as nx

# Create a random DAG
G = nx.gnp_random_graph(50,0.3,directed=True)
DAG = nx.DiGraph([(u,v) for (u,v) in G.edges() if u<v])
nx.is_directed_acyclic_graph(DAG)
for edge in G.edges:
    G.edges[edge]['weight'] = 1

# Get the longest path (without weights) from node 1 to node 40
# with nodes 5, 10, 20, 30 inside
max([
    (path, len(path))
    for path in nx.all_simple_paths(DAG, 1, 40)
    if all(n in path for n in (5, 10, 20, 30))
], key=lambda x: x[1])

# Get the longest path (with weights)
max([
    path
    for path in nx.all_simple_paths(DAG, 1, 40)
    if all(n in path for n in (5, 10, 20, 30))
], key=lambda x: sum(G.edges[edge]['weight'] for edge in nx.utils.pairwise(x)))

关于python - networkx 中具有 'key' 个节点可访问的最短路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56460584/

相关文章:

python - 尝试使用 TkAgg 后端进行绘图时 Mac OS 崩溃

python - 在启动 cron 时从 Python 访问文件系统

python - 如何使异步池可取消?

python - 将有向图划分为 n 个 block

python - 使用 matplotlib.pyplot 时如何显示节点标签?

python - 共享引用和平等

python - 如何根据一系列值对数据帧行进行有效分类?

python - 绘制包含许多组件的图形时节点大小不正确

python - 来自不同数据集的节点属性

python - 使用networkx按属性绘制节点形状和节点颜色