Select Git revision
-
hamza masmoudi authoredhamza masmoudi authored
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))