How to detect a cycle in a directed graph with Python?

前端 未结 3 983
你的背包
你的背包 2020-12-02 00:59

I have some input like: [(\'A\', \'B\'),(\'C\', \'D\'),(\'D\', \'C\'),(\'C\', \'D\')]. I want to look for if the existence of a cycle in a directed graph repres

3条回答
  •  一个人的身影
    2020-12-02 01:28

    Using the networkx library, we can use the simple_cycles function to find all simple cycles of a directed Graph.

    Example Code:

    import networkx as nx
    
    edges = [('A', 'B'),('C', 'D'),('D', 'C'),('C', 'D')]
    
    G = nx.DiGraph(edges)
    
    for cycle in nx.simple_cycles(G):
        print(cycle)
    
    G = nx.DiGraph()
    
    G.add_edge('A', 'B')
    G.add_edge('B', 'C')
    G.add_edge('C', 'A')
    
    for cycle in nx.simple_cycles(G):
        print(cycle)
    

    Output:

    ['D', 'C']
    ['B', 'C', 'A']
    

提交回复
热议问题