Open In App
Related Articles

Algorithms | Graph Traversals | Question 9

Improve Article
Save Article
Like Article

Which of the following condition is sufficient to detect cycle in a directed graph?


There is an edge from currently being visited node to an already visited node.


There is an edge from currently being visited node to an ancestor of currently visited node in DFS forest.


Every node is seen twice in DFS.


None of the above

Answer: (B)


To find cycle in a directed graph we can use the Depth First Traversal (DFS) technique. It is based on the idea that there is a cycle in a graph only if there is a back edge [i.e., a node points to one of its ancestors] present in the graph.

To detect a back edge, we need to keep track of the nodes visited till now and the nodes that are in the current recursion stack [i.e., the current path that we are visiting]. If during recursion, we reach a node that is already in the recursion stack, there is a cycle present in the graph.

If the graph is disconnected then get the DFS forest and check for a cycle in individual trees by checking back edges.

Hence Option(B) is the correct answer.

Quiz of this Question
Please comment below if you find anything wrong in the above post

Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads