import networkx as nx
G = nx.Graph()
G.add_edges_from([[0,1], [1,2], [2,3], [0,2], [0,3]])
X = nx.shortest_simple_paths(G, 0, 3) #generator to find paths from 0 to 3 in order from shortest to longest.
for x in X:
print(x)
> [0, 3]
> [0, 2, 3]
> [0, 1, 2, 3]
#note that X is now empty because it is a generator
for x in X:
print(x) #nothing to see here
>
#if you just want the first two:
X = nx.shortest_simple_paths(G, 0, 3)
for k in range(2):
print(next(X))
> [0, 3]
> [0, 2, 3]
Networkx有一个内置算法,可以生成最短路径、下一个最短路径、下一个最短路径等
它是shortest_simple_paths。在
例如:
该算法可以找到所有的路径,但它的设置是这样的:当被要求时,它只做额外的工作来计算第k条最短路径,然后忘记它。有关生成器的更多信息,请参见Understanding generators in Python。在
相关问题 更多 >
编程相关推荐