Open In App

Algorithms | Graph Traversals | Question 9

Like Article
Like
Save Article
Save
Share
Report issue
Report

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

(A)

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

(B)

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

(C)

Every node is seen twice in DFS.

(D)

None of the above



Answer: (B)

Explanation:

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
Previous
Next
Share your thoughts in the comments
Similar Reads