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
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 colors
- Detect cycle in an undirected graph using BFS
- Detect a negative cycle in a Graph using Shortest Path Faster Algorithm
- Detect Cycle in a Directed Graph using BFS
- Detect cycle in Directed Graph using Topological Sort
- Sum of degrees of all nodes of a undirected graph
- Difference Between sum of degrees of odd and even degree nodes in an Undirected Graph
- Detect Cycle in a Directed Graph
- Detect cycle in an undirected graph
- Detect a negative cycle in a Graph | (Bellman Ford)
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Detect Cycle in a Linked List using Map
- Print nodes having maximum and minimum degrees
- Detect Cycle in a 2D grid
- Check whether given degrees of vertices represent a Graph or Tree
- Construct a graph from given degrees of all vertices
- Finding in and out degrees of all vertices in a graph
- Print Nodes which are not part of any cycle in a Directed Graph
- Number of trees whose sum of degrees of all the vertices is L
- Maximize count of nodes disconnected from all other nodes in a 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.