how to detect cycle in directed graph using depth first search.Detecting cycle in directed graph using depth first traversal is one of use case of DFS. for example in below example directed graph there are two cycles in it, one is 0>2>3>0 and second one is 2>3>4>5>2.

how to detect cycle in directed graph using depth first search

how to detect cycle in directed graph using depth first search

 The below implementation of cycle detection in directed graph is using the fact “During dfs if we found a vertex which is already on the stack that means there is loop”. The unvisited node is colored white and the nodes which are on the stack is colored with gray. The finished node is colored black.