简体   繁体   中英

Find all cycles in directed and undirected graph

I want to be able to find all cycles in a directed and an undirected graph.

The below code returns True or False if a cycle exists or not in a directed graph:

def cycle_exists(G):                     
    color = { u : "white" for u in G  }  
    found_cycle = [False]               

    for u in G:                          
        if color[u] == "white":
            dfs_visit(G, u, color, found_cycle)
        if found_cycle[0]:
            break
    return found_cycle[0]


def dfs_visit(G, u, color, found_cycle):
    if found_cycle[0]:                         
        return
    color[u] = "gray"                         
    for v in G[u]:                              
        if color[v] == "gray":                  
            found_cycle[0] = True       
            return
        if color[v] == "white":                    
            dfs_visit(G, v, color, found_cycle)
    color[u] = "black"

The below code returns True or False if a cycle exists or not in an undirected graph:

def cycle_exists(G):                                 
    marked = { u : False for u in G }    
    found_cycle = [False]                                                       

    for u in G:                          
        if not marked[u]:
            dfs_visit(G, u, found_cycle, u, marked)     
        if found_cycle[0]:
            break
    return found_cycle[0]

def dfs_visit(G, u, found_cycle, pred_node, marked):
    if found_cycle[0]:                             
        return
    marked[u] = True                                 
    for v in G[u]:                                    
        if marked[v] and v != pred_node:             
            found_cycle[0] = True                     
            return
        if not marked[v]:                            
            dfs_visit(G, v, found_cycle, u, marked)

graph_example = { 0 : [1],
                  1 : [0, 2, 3, 5],  
                  2 : [1],
                  3 : [1, 4],
                  4 : [3, 5],
                  5 : [1, 4] }

How do I use these to find all the cycles that exist in a directed and undirected graph?

If I understand well, your problem is to use one unique algorithm for directed and undirected graph.

Why can't you use the algorithm to check for directed cycles on undirected graph? Non-directed graphs are a special case of directed graphs . You can just consider that a undirected edge is made from one forward and backward directed edge.

But, this is not very efficient. Generally, the statement of your problem will indicate if the graph is or not directed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM