[英]Shortest Path in networkx with 'key' nodes to visit
I have a directed graph in python G developed with networkx. 我在用networkx开发的python G中有一个有向图。 The graph has weights called 'weight'.
该图的权重称为“权重”。
I know an explicit start node A and an End Node F. In between the graph can access the nodes B,C,D,E. 我知道显式的起始节点A和结束节点F。在图之间可以访问节点B,C,D,E。
How can i explicity say that he has to acces B and D by finding the shortest path and can addionally add C and E, if this helps to the shortest path? 我该如何明确地说他必须通过找到最短路径来访问B和D,并且可以附加地添加C和E(如果这有助于最短路径)?
So far I know the function: 到目前为止,我知道函数:
nx.single_source_dijkstra(G, 'A', target='F', cutoff=None, weight='weight')
which gives the output: 它给出了输出:
(10.01,
['A',
'B',
'C',
'F',])
How can I make sure that it includes E? 我如何确保它包含E?
Networkx has no built-in functions or arguments for your problem. Networkx没有针对您的问题的内置函数或参数。 You should do it manually:
您应该手动进行:
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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.