我需要找到有向图中每对节点之间的最短路径。我的做法是:
for i in A.nodes()
for y in A.nodes()
paths = nx.all_shortest_paths(G,i,y)
但是这个过程非常缓慢,我猜想这是因为在图中有很多节点与i没有任何连接。有没有一种优化这个过程的方法?我已经确保那些不可能与其他节点相连的节点不会最终出现在A中。
我需要找到有向图中每对节点之间的最短路径。我的做法是:
for i in A.nodes()
for y in A.nodes()
paths = nx.all_shortest_paths(G,i,y)
但是这个过程非常缓慢,我猜想这是因为在图中有很多节点与i没有任何连接。有没有一种优化这个过程的方法?我已经确保那些不可能与其他节点相连的节点不会最终出现在A中。
有一个内置命令:single_source_shortest_path_length(G, source)
可以给出源节点和每个可达节点之间的最短路径。
import networkx as nx
G=nx.DiGraph()
G.add_edges_from([(1,2), (2,3), (3,4), (1,5), (2,5), (6,7)]) #6,7 not reachable from 1
nx.single_source_shortest_path(G,1)
>{1: [1], 2: [1, 2], 3: [1, 2, 3], 4: [1, 2, 3, 4], 5: [1, 5]}
问题标题表明你只想知道可达节点而不是路径。在这种情况下,使用深度优先搜索或广度优先搜索。文档可以在这里找到。例如:dfs_postorder_nodes(G, source=None)
为从源节点可达的节点提供了一个迭代器。它们出现的特定顺序是深度优先搜索后序。
for reachable_node in nx.dfs_postorder_nodes(G,source=1):
print reachable_node
>4
>3
>5
>2
>1
nx.descendants
查找可达节点。请参见 https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.dag.descendants.html - JanLikarfor n1 in G for n2 in G
的等效操作,但正如我所说,如果你将节点放入一个列表中,然后对整个列表进行索引以获取第一个节点,对第一个节点之后的所有节点进行索引,例如(nlist[i], nlist[j]) for i in range(len(nlist)) for j in range(i+1, len(nlist))
,你可以缩短它。