Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1.
Output: 0 1 2
Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vertices to their degrees.
Initially, traverse the map and store all the vertices with degree = 1 in a queue. Traverse the queue as long as it is not empty. For each node in the queue, mark it as visited, and iterate through all the nodes that are connected to it (using the adjacency list), and decrement the degree of each of those nodes by one in the map. Add all nodes whose degree becomes equal to one to the queue. At the end of this algorithm, all the nodes that are unvisited are part of the cycle.
Below is the implementation of the above approach:
0 1 2
- Detect cycle in an undirected graph
- Detect Cycle in a Directed Graph using BFS
- Detect Cycle in a Directed Graph
- Detect cycle in an undirected graph using BFS
- Detect Cycle in a directed graph using colors
- Detect a negative cycle in a Graph | (Bellman Ford)
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Sum of degrees of all nodes of a undirected graph
- Construct a graph from given degrees of all vertices
- Finding in and out degrees of all vertices in a graph
- Check whether given degrees of vertices represent a Graph or Tree
- Coloring a Cycle Graph
- Degree of a Cycle Graph
- Check if there is a cycle with odd weight sum in an undirected graph
- Find minimum weight cycle 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.