Skip to content
Snippets Groups Projects
Select Git revision
  • 46275f6bbac408a68bcf61b9251f00edbeb2bf7a
  • master default protected
2 results

exceptions.py

Blame
  • graph-cycle.py 986 B
    graph = { 0 : [1], 1 : [2], 2 : [3], 3 : [4], 4 : [1] }
    # https://algocoding.wordpress.com/2015/04/02/detecting-cycles-in-a-directed-graph-with-dfs-python/
    def cycle_existe(G):                    
        color = { u : "white" for u in G  }  # Noeuds tous blancs
        trouve_cycle = [False]                 
     
        for u in G:                          # On visite tous les noeuds
            if color[u] == "white":
                dfs_visite(G, u, color, trouve_cycle)
            if trouve_cycle[0]:
                break
        return trouve_cycle[0]
     
    def dfs_visite(G, u, color, trouve_cycle):
        if trouve_cycle[0]:                         
            return
        color[u] = "gray"                  
        for v in G[u]:                             
            if color[v] == "gray":                 
                trouve_cycle[0] = True       
                return
            if color[v] == "white":                
                dfs_visite(G, v, color, trouve_cycle)
        color[u] = "black"   
    
    print(cycle_existe(graph))