Created
February 20, 2021 16:23
-
-
Save prem0862/b2de272693f7a1645e739bde9ece7b51 to your computer and use it in GitHub Desktop.
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 detect_cycle(node, graph, visited, parent): | |
visited.add(node) | |
for neigh in graph[node]: | |
if neigh not in visited: | |
cycle = detect_cycle(neigh, graph, visited, node) | |
if cycle == True: | |
return True | |
else: | |
if parent != neigh: | |
return True | |
return False | |
if __name__ == "__main__": | |
graph = { | |
1: [2], | |
2: [3], | |
3: [4], | |
4: [5], | |
5: [1] | |
} | |
visited = set() | |
is_cycle = detect_cycle(1, graph, visited, None) | |
print(is_cycle) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment