Given an undirected graph, how to check if there is a cycle in the graph? For example, the following graph has a cycle 1-0-2-1.
We have discussed cycle detection for directed graph. We have also discussed a union-find algorithm for cycle detection in undirected graphs. The time complexity of the union-find algorithm is O(ELogV). Like directed graphs, we can use DFS to detect cycle in an undirected graph in O(V+E) time. We do a DFS traversal of the given graph. For every visited vertex ‘v’, if there is an adjacent ‘u’ such that u is already visited and u is not parent of v, then there is a cycle in graph. If we don’t find such an adjacent for any vertex, we say that there is no cycle. The assumption of this approach is that there are no parallel edges between any two vertices.
// 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