Data Structures & AlgorithmsVery hardTCS NQT · Infosys pattern
A directed graph has edges C→B, B→D, A→D, C→A, C→D, A→C. Using 3-colour DFS (white/grey/black, a grey-to-grey back edge means a cycle), does this graph contain a cycle?
- A. Cannot be determined without running BFS
- B. Yes, but only a self-loop
- C. Yes, it has a cycle
- D. No, it is a DAG
Correct answer: C. Yes, it has a cycle
DFS marks a vertex grey while it's on the current recursion stack and black once fully explored; finding an edge into a grey vertex means a back edge, i.e. a cycle. Running this on the given edges gives: "Yes, it has a cycle". An edge into an already-black vertex is a forward/cross edge and does not indicate a cycle by itself.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Directed edges: A→B (6), A→C (6), C→B (-3), B→D (1). Dijkstra's algorithm, which finalises each vertex once when it is removed from the…
- A directed graph has edges D→B, C→B, B→A, D→C, B→C. Using 3-colour DFS (white/grey/black, a grey-to-grey back edge means a cycle), does…
- Directed edges: A→B (5), A→C (6), C→B (-3), B→D (3). Dijkstra's algorithm, which finalises each vertex once when it is removed from the…
- Keys 34, 69, 39, 53, 61, 76, 35 are inserted in this order into an empty BST (no rebalancing). What is the height of the tree (edges on…
- An undirected graph has adjacency lists (neighbours visited in alphabetical order) A: [C, E, F]; B: [C, E]; C: [A, B, F]; D: [F]; E: [A…
- An undirected graph has adjacency lists (neighbours visited in alphabetical order) A: [B, C, F]; B: [A, C, D]; C: [A, B]; D: [B, E, F]; E…