13,401 views
1 votes
1 votes

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 bove

 

here option B is right, but why not option A?

1 Answer

1 votes
1 votes

Depth First Traversal can be used to detect a cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is from a node to itself (self-loop) or one of its ancestor in the tree produced by DFS. 

For a disconnected graph, we get the DFS forest as output. To detect cycle, we can check for a cycle in individual trees by checking back edges.

To detect a back edge, we can keep track of vertices currently in recursion stack of function for DFS traversal. If we reach a vertex that is already in the recursion stack, then there is a cycle in the tree. The edge that connects current vertex to the vertex in the recursion stack is a back edge.

Time Complexity of this method is the same as time complexity of DFS traversal which is O(V+E).

Related questions

0 votes
0 votes
2 answers
2
radha gogia asked Aug 5, 2015
2,168 views
Does it tale constant time or the time taken proportional to search in the entire partition of elements to find whether the component lies in that same component or not ?...
1 votes
1 votes
2 answers
3
Gate Aspirant 2 asked Dec 19, 2014
2,489 views
Which of the following statement is correct regarding DFS? 1) All the vertices are pushed in the stack during DFS Traversal. 2) No vertex is pushed more than once in the ...
2 votes
2 votes
0 answers
4
rahul sharma 5 asked Apr 5, 2018
819 views
Write $O(n)$ time algorithm to find any cycles in a graph. Print NONE otherwise