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 have discussed DFS based solution for cycle detection in undirected graph.
In this article, BFS based solution is discussed. We do a BFS 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.
We use a parent array to keep track of parent vertex for a vertex so that we do not consider visited parent as cycle.
Time Complexity: The program does a simple BFS Traversal of graph and graph is represented using adjacency list. So the time complexity is O(V+E)
- Detect cycle in an undirected graph
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Detect Cycle in a Directed Graph using BFS
- Detect Cycle in a Directed Graph
- Detect Cycle in a directed graph using colors
- Detect a negative cycle in a Graph | (Bellman Ford)
- Check if there is a cycle with odd weight sum in an undirected graph
- Find minimum weight cycle in an undirected graph
- Number of single cycle components in an undirected graph
- Clone an Undirected Graph
- Number of Triangles in an Undirected Graph
- Find k-cores of an undirected graph
- Eulerian Path in undirected graph
- Connected Components in an undirected graph
- Print all the cycles in an undirected graph
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.