Skip to content

Instantly share code, notes, and snippets.

@arekbulski
Created December 2, 2015 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arekbulski/fd95148d421d9882e03d to your computer and use it in GitHub Desktop.
Save arekbulski/fd95148d421d9882e03d to your computer and use it in GitHub Desktop.
def dfs(graph, start):
color = {i : 'white' for i in graph}
stack = [start]
visited = []
while stack:
vertex = stack.pop()
if color[vertex] == 'grey':
return True
color[vertex] = 'grey'
visited.append(vertex)
stack.extend((graph[vertex]))
if len(graph[vertex]) == 0:
color[vertex] = 'black'
return False
def cycle_exists(graph):
for vertex in graph:
if(dfs(graph, vertex)):
return True
return False
graph1 = { 0 : [],
1 : [2,3],
2 : [4],
3 : [4],
4 : [5],
5 : [] }
assert(not cycle_exists(graph1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment