Data Structures & AlgorithmsHardProduct company OA

DFS with white/grey/black colours detects a cycle in the directed graph with adjacency lists 1: [2, 3], 2: [4], 3: [4], 4: [5], 5: [3], starting at 1 and visiting neighbours in order. Which edge is the FIRST one found to point to a grey vertex (a back edge)?

  1. A. 3 → 4
  2. B. 5 → 3
  3. C. 4 → 5
  4. D. 1 → 3

Correct answer: A. 3 → 4

DFS goes 1 → 2 → 4 → 5; from 5 the edge 5 → 3 leads to WHITE 3, so 3 is explored (grey path now 1, 2, 4, 5, 3). From 3 the edge 3 → 4 hits 4, which is still grey → back edge 3 → 4, and the cycle is 4 → 5 → 3 → 4. Expecting 5 → 3 assumes 3 was visited first via 1 → 3.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic