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.
Create the graph using the given number of edges and vertices.
Create a recursive function that that 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.
link brightness_4 code
// A C++ Program to detect cycle in an undirected graph
// Class for an undirected graph
intV; // No. of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
boolisCyclicUtil(intv, boolvisited, intparent);
Graph(intV); // Constructor
voidaddEdge(intv, intw); // to add an edge to graph
boolisCyclic(); // returns true if there is a cycle
this->V = V;
adj = newlist<int>[V];
adj[v].push_back(w); // Add w to v’s list.
adj[w].push_back(v); // Add v to w’s list.
// A recursive function that uses visited and parent to detect