当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。