Skip to content

Instantly share code, notes, and snippets.

@PeterWaIIace
Created December 7, 2023 23:41
Show Gist options
  • Save PeterWaIIace/39644c807b5bb4c58d1e06ccef9a23cb to your computer and use it in GitHub Desktop.
Save PeterWaIIace/39644c807b5bb4c58d1e06ccef9a23cb to your computer and use it in GitHub Desktop.
Find cycles in graph with DFS
def has_cycle(graph):
visited = set()
recursion_stack = set()
def dfs(node):
visited.add(node)
recursion_stack.add(node)
for child in graph[node]:
print(f"{child} and {recursion_stack}")
if child not in visited:
if dfs(child):
return True
elif child in recursion_stack:
return True
recursion_stack.remove(node)
return False
first = list(graph.keys())[0]
return dfs(first)
# Example graph as an adjacency list (with a cycle)
graph_with_cycle = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D'],
'D': ['A']
}
# Example graph as an adjacency list (acyclic)
graph_acyclic = {
'A': ['D', 'B', 'C'],
'B': ['D'],
'C': ['D'],
'D': ['F','E'],
'F': [],
'E': []
}
print("Has Cycle (Graph with Cycle):", has_cycle(graph_with_cycle)) # Output: True
print("Has Cycle (Acyclic Graph):", has_cycle(graph_acyclic)) # Output: False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment