Skip to main content

Detect Graph Cycle

Definition​

The Detect Cycle Algorithm in Graph is used to identify if a graph contains cycles, i.e., closed loops where a sequence of edges returns to a vertex. It's crucial for various applications such as network routing, deadlock detection, and more. This algorithm typically employs Depth-First Search (DFS) or Union-Find to traverse the graph and detect cycles efficiently

Practice​

hasCycle(graph):
visited = set() // Set to keep track of visited vertices
for vertex in graph.vertices:
if vertex not in visited:
if dfs(vertex, visited, None): // Start DFS from current vertex
return true // If cycle detected, return true
return false // If no cycle detected, return false

dfs(vertex, visited, parent):
visited.add(vertex) // Mark current vertex as visited
for neighbor in vertex.neighbors:
if neighbor not in visited: // If neighbor not visited, recursively call DFS
if dfs(neighbor, visited, vertex):
return true // If cycle detected, return true
else if neighbor != parent: // If neighbor is visited and not parent, cycle detected
return true
return false // If no cycle detected, return false