Finding all cycles in a directed graph

前端 未结 17 2213
渐次进展
渐次进展 2020-11-22 05:47

How can I find (iterate over) ALL the cycles in a directed graph from/to a given node?

For example, I want something like this:

A->B->A
A->B         


        
17条回答
  •  再見小時候
    2020-11-22 06:02

    The simplest choice I found to solve this problem was using the python lib called networkx.

    It implements the Johnson's algorithm mentioned in the best answer of this question but it makes quite simple to execute.

    In short you need the following:

    import networkx as nx
    import matplotlib.pyplot as plt
    
    # Create Directed Graph
    G=nx.DiGraph()
    
    # Add a list of nodes:
    G.add_nodes_from(["a","b","c","d","e"])
    
    # Add a list of edges:
    G.add_edges_from([("a","b"),("b","c"), ("c","a"), ("b","d"), ("d","e"), ("e","a")])
    
    #Return a list of cycles described as a list o nodes
    list(nx.simple_cycles(G))
    

    Answer: [['a', 'b', 'd', 'e'], ['a', 'b', 'c']]

提交回复
热议问题