Approach: This problem can be solved using DFS of Graph and Stack to store vertices of Graph.
Create a variable x to store starting of the cycle and create a stack to store the vertices of the cycle.
DFS traverses the given graph and marks the node as visited.
For every child of this node check if the child has not visited DFS traverse the child.
Otherwise, if the child is visited and also it is not the parent of the current node then we have detected the cycle and thus the value of x becomes the child node value.
Below is the implementation of the above approach:
Output
Cycle exists.
3 -> 2 -> 1
Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges in the graph. Auxiliary Space: O(V) where V is the number of vertices in the graph.
Another Method: Check cycle exists or Not:-
For finding the cycle in an undirected graph we use DFS. Use dfs from every unvisited node. There is a cycle in an undirected graph only if there is a back edge present in the graph. To find the back edge to any of its ancestors keep a visited array and if there is a back edge to any visited node then there is a loop and return true.
Approach:
Follow the below steps to implement the above approach:
First iterate over all the nodes of the graph and keep vis[] array for keeping the track of the visited nodes.
Run a DFS (Depth First Search) traversal on the given subgraph connected to the current node and then pass the parent of the current node.
For every recursion set vis[root] = 1.
Iterate over all adjacent nodes of the current node in the adjacency list
if it is not visited
then run DFS on that node, return the result of the DFS.
Else if the adjacent node is visited
if it is not the parent of the current node
then return true.
else return false.
Output:
Graph1 contains cycle
Complexity:
Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges in the graph. Auxiliary Space: O(V) where V is the number of vertices in the graph.