Detect Cycle in a Directed Graph

Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false.

Example,

Input: n = 4, e = 6
0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3
Output: Yes
Explanation:
Diagram:
The diagram clearly shows a cycle 0 -> 2 -> 0 Input:n = 4, e = 3 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 3 Output:No Explanation: Diagram:
The diagram clearly shows no cycle

Solution using Depth First Search or DFS

In the below article, another O(V + E) method is discussed :
Detect Cycle in a direct graph using colors

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

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.





Article Tags :