-
Notifications
You must be signed in to change notification settings - Fork 68
/
Detect Cycle in Undirected Graph Algo
11 lines (10 loc) · 1.13 KB
/
Detect Cycle in Undirected Graph Algo
1
2
3
4
5
6
7
8
9
10
11
Approach: Run a DFS from every unvisited node. Depth First Traversal can be used to detect a cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is joining a node to itself (self-loop) or one of its ancestor in the tree produced by DFS.
To find the back edge to any of its ancestor keep a visited array and if there is a back edge to any visited node then there is a loop and return true.
Algorithm:
Create the graph using the given number of edges and vertices.
Create a recursive function that have current index or vertex, visited array and parent node.
Mark the current node as visited .
Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true return true.
If the adjacent node is not parent and already visited then return true.
Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true, return true.
Else if for all vertices the function returns false return false.