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)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Detect cycle in an undirected graph
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Detect cycle in the graph using degrees of nodes of graph
- Detect Cycle in a Directed Graph
- Detect Cycle in a Directed Graph using BFS
- Shortest cycle in an undirected unweighted graph
- Check if there is a cycle with odd weight sum in an undirected graph
- Detect Cycle in a directed graph using colors
- Number of single cycle components in an undirected graph
- Find minimum weight cycle in an undirected graph
- Detect a negative cycle in a Graph | (Bellman Ford)
- Minimum labelled node to be removed from undirected Graph such that there is no cycle
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Convert undirected connected graph to strongly connected directed graph
- Clone 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 firstname.lastname@example.org. 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.