Find all cycles in directed and undirected graph
<p>I want to be able to find all cycles in a directed and an undirected graph. </p>

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

<pre><code>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"
</code></pre>

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

<pre><code>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] }
</code></pre>

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

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

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

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

python graph graph-theory dfs