Approach: 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 from a node to itself (self-loop) or one of its ancestors in the tree produced by DFS. In the following graph, there are 3 back edges, marked with a cross sign. We can observe that these 3 back edges indicate 3 cycles present in the graph.
For a disconnected graph, Get the DFS forest as output. To detect cycle, check for a cycle in individual trees by checking back edges. To detect a back edge, keep track of vertices currently in the recursion stack of function for DFS traversal. If a vertex is reached that is already in the recursion stack, then there is a cycle in the tree. The edge that connects the current vertex to the vertex in the recursion stack is a back edge. Use recStack array to keep track of vertices in the recursion stack. Dry run of the above approach:
In the above image there is a mistake node 1 is making a directed edge to 2 not with 0 please make a note.
Create the graph using the given number of edges and vertices.
Create a recursive function that initializes the current index or vertex, visited, and recursion stack.
Mark the current node as visited and also mark the index in recursion stack.
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 vertices are already marked in the recursion stack 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.
// A C++ Program to detect cycle in a graph
intV; // No. of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
boolisCyclicUtil(intv, boolvisited, bool*rs); // used by isCyclic()
Graph(intV); // Constructor
voidaddEdge(intv, intw); // to add an edge to graph
boolisCyclic(); // returns true if there is a cycle in this graph