Solution: Detect a Cycle in a Graph
This review provides a detailed analysis of the different ways to solve the Detect a Cycle in a Graph challenge.
We'll cover the following...
Solution:
def detect_cycle(graph):"""Detects a cycle in a given graph:param graph: The graph:return: True if there is a cycle in the given graph, otherwise False"""# visited list to keep track of the nodes that have been visited since the beginning of the algorithmvisited = [False] * graph.V# stack keeps track of the nodes which are part of the current recursive callmy_stack = [False] * graph.Vfor node in range(graph.V):# DFSif detect_cycle_recursive(graph, node, visited, my_stack):return Truereturn Falsedef detect_cycle_recursive(graph, node, visited, my_stack):"""Detects a cycle in a given graph:param graph: The graph:param node: A source vertex:param visited: A list to track visited nodes:param stack: A helper stack:return: True if there is a cycle in the given graph, otherwise False"""# Node was already in recursion stack. Cycle found.if my_stack[node]:return True# It has been visited before this recursionif visited[node]:return False# Mark current node as visited and# add to recursion stackvisited[node] = Truemy_stack[node] = Truehead = graph.graph[node]while head is not None:# Pick adjacent node and call it recursivelyadjacent = head.vertex# If the node is visited again in the same recursion => Cycle foundif detect_cycle_recursive(graph, adjacent, visited, my_stack):return Truehead = head.next# remove the node from the recursive callmy_stack[node] = Falsereturn False# Main program to test the above codeif __name__ == "__main__":g1 = Graph(4)g1.add_edge(0, 1)g1.add_edge(1, 2)g1.add_edge(1, 3)g1.add_edge(3, 0)g2 = Graph(3)g2.add_edge(0, 1)g2.add_edge(1, 2)print(detect_cycle(g1))print(detect_cycle(g2))
Explanation
The solution might look ...
Access this course and 1400+ top-rated courses and projects.