Networkx 有一个内置算法,可以生成最短路径,然后是下一条最短路径,然后是下一条最短路径,等等。
是shortest_simple_paths。
例如:
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]
这个算法会找到所有的路径,但是它被设置成它只做额外的工作来计算第 k 条最短路径,当它被要求时,它会忘记它。有关生成器的更多信息,请参阅 Understanding generators in Python。