Skip to content

Instantly share code, notes, and snippets.

@prem0862
Created February 20, 2021 16:23
Show Gist options
  • Save prem0862/b2de272693f7a1645e739bde9ece7b51 to your computer and use it in GitHub Desktop.
Save prem0862/b2de272693f7a1645e739bde9ece7b51 to your computer and use it in GitHub Desktop.
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