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)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Detect Cycle in a Directed Graph using BFS
- 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 using colors
- Detect a negative cycle in a Graph using Shortest Path Faster Algorithm
- Detect cycle in Directed Graph using Topological Sort
- Find minimum weight cycle in an undirected graph
- Check if there is a cycle with odd weight sum in an undirected graph
- Number of single cycle components in an undirected graph
- Shortest cycle in an undirected unweighted graph
- Minimum labelled node to be removed from undirected Graph such that there is no cycle
- Find any simple cycle in an undirected unweighted Graph
- Detect Cycle in a Directed Graph
- Detect a negative cycle in a Graph | (Bellman Ford)
- 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
- Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
- Islands in a graph using BFS
- Detect Cycle in a 2D grid
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.