Created
December 7, 2023 23:41
-
-
Save PeterWaIIace/39644c807b5bb4c58d1e06ccef9a23cb to your computer and use it in GitHub Desktop.
Find cycles in graph with DFS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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