當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python NetworkX all_simple_paths用法及代碼示例


本文簡要介紹 networkx.algorithms.simple_paths.all_simple_paths 的用法。

用法:

all_simple_paths(G, source, target, cutoff=None)

生成圖 G 中從源到目標的所有簡單路徑。

簡單路徑是沒有重複節點的路徑。

參數

GNetworkX 圖
source節點

路徑的起始節點

target節點

結束路徑的單個節點或節點的可迭代

cutoff整數,可選

停止搜索的深度。僅返回長度 <= 截止的路徑。

返回

path_generator:生成器

生成簡單路徑列表的生成器。如果在給定的截止範圍內源和目標之間沒有路徑,則生成器不會產生輸出。

注意

該算法使用修改後的深度優先搜索來生成路徑 [1]。在 時間內可以找到一條路徑,但圖中簡單路徑的數量可能非常大,例如 的完整圖中的

此函數不檢查 sourcetarget 之間是否存在路徑。對於大圖,這可能會導致運行時間很長。考慮使用has_path 來檢查sourcetarget 之間是否存在路徑,然後再在大圖上調用此函數。

參考

1

R. Sedgewick, “Algorithms in C, Part 5: Graph Algorithms”, Addison Wesley Professional, 3rd ed., 2001.

例子

此迭代器生成節點列表:

>>> G = nx.complete_graph(4)
>>> for path in nx.all_simple_paths(G, source=0, target=3):
...     print(path)
...
[0, 1, 2, 3]
[0, 1, 3]
[0, 2, 1, 3]
[0, 2, 3]
[0, 3]

您可以使用 cutoff 關鍵字參數僅生成短於特定長度的路徑:

>>> paths = nx.all_simple_paths(G, source=0, target=3, cutoff=2)
>>> print(list(paths))
[[0, 1, 3], [0, 2, 3], [0, 3]]

要將每條路徑作為對應的邊列表,您可以使用networkx.utils.pairwise() 輔助函數:

>>> paths = nx.all_simple_paths(G, source=0, target=3)
>>> for path in map(nx.utils.pairwise, paths):
...     print(list(path))
[(0, 1), (1, 2), (2, 3)]
[(0, 1), (1, 3)]
[(0, 2), (2, 1), (1, 3)]
[(0, 2), (2, 3)]
[(0, 3)]

將節點的可迭代作為目標傳遞,以生成以多個節點中的任何一個結尾的所有路徑:

>>> G = nx.complete_graph(4)
>>> for path in nx.all_simple_paths(G, source=0, target=[3, 2]):
...     print(path)
...
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 3]
[0, 1, 3, 2]
[0, 2]
[0, 2, 1, 3]
[0, 2, 3]
[0, 3]
[0, 3, 1, 2]
[0, 3, 2]

使用函數式編程方法在有向無環圖中迭代從根節點到葉節點的每條路徑:

>>> from itertools import chain
>>> from itertools import product
>>> from itertools import starmap
>>> from functools import partial
>>>
>>> chaini = chain.from_iterable
>>>
>>> G = nx.DiGraph([(0, 1), (1, 2), (0, 3), (3, 2)])
>>> roots = (v for v, d in G.in_degree() if d == 0)
>>> leaves = (v for v, d in G.out_degree() if d == 0)
>>> all_paths = partial(nx.all_simple_paths, G)
>>> list(chaini(starmap(all_paths, product(roots, leaves))))
[[0, 1, 2], [0, 3, 2]]

使用迭代方法計算的相同列表:

>>> G = nx.DiGraph([(0, 1), (1, 2), (0, 3), (3, 2)])
>>> roots = (v for v, d in G.in_degree() if d == 0)
>>> leaves = (v for v, d in G.out_degree() if d == 0)
>>> all_paths = []
>>> for root in roots:
...     for leaf in leaves:
...         paths = nx.all_simple_paths(G, root, leaf)
...         all_paths.extend(paths)
>>> all_paths
[[0, 1, 2], [0, 3, 2]]

在有向無環圖中遍曆從根節點到葉子節點的每條路徑,將所有葉子一起傳遞以避免不必要的計算:

>>> G = nx.DiGraph([(0, 1), (2, 1), (1, 3), (1, 4)])
>>> roots = (v for v, d in G.in_degree() if d == 0)
>>> leaves = [v for v, d in G.out_degree() if d == 0]
>>> all_paths = []
>>> for root in roots:
...     paths = nx.all_simple_paths(G, root, leaves)
...     all_paths.extend(paths)
>>> all_paths
[[0, 1, 3], [0, 1, 4], [2, 1, 3], [2, 1, 4]]

相關用法


注:本文由純淨天空篩選整理自networkx.org大神的英文原創作品 networkx.algorithms.simple_paths.all_simple_paths。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。