【问题标题】:How can I find circular relations in a graph with Python and Networkx?如何使用 Python 和 Networkx 在图中找到循环关系?
【发布时间】:2012-02-21 18:00:30
【问题描述】:

假设我有以下图表:

A -> B
B -> C
C -> D
C -> A

找到 A -> B -> C -> A 是循环关系的最简单方法是什么? NetworkX 或其他易于使用的 Python 库中是否已经内置了这样的功能?

【问题讨论】:

    标签: python algorithm graph-theory networkx


    【解决方案1】:

    networkx.simple_cycles 为你做这件事。

    >>> import networkx as nx
    >>> G = nx.DiGraph()
    >>> G.add_edge('A', 'B')
    >>> G.add_edge('B', 'C')
    >>> G.add_edge('C', 'D')
    >>> G.add_edge('C', 'A')
    >>> nx.simple_cycles(G)
    [['A', 'B', 'C', 'A']]
    

    【讨论】:

      【解决方案2】:

      使用Depth-First Search 检测图中的循环。

      【讨论】:

        猜你喜欢
        • 2019-03-07
        • 1970-01-01
        • 2018-10-21
        • 1970-01-01
        • 2013-04-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        相关资源
        最近更新 更多