Data Structures & AlgorithmsModerateGATE CS 2 marks · Codeforces Div 2 B

Undirected graph on vertices 0 to 7 with edges listed as: 1–4, 2–3, 1–3, 0–3, 0–5, 2–7, 4–5, 1–6, 6–7, 3–5, 0–6, 0–1. The adjacency list of each vertex is built by scanning this list in order (an edge u–v is appended to u's list, then to v's list). A recursive depth-first search starts at 0 and, at each vertex, tries neighbours in list order. What is the preorder sequence (the order in which vertices are first visited)?

  1. A. 0 3 5 6 1 2 4 7
  2. B. 0 1 6 7 2 3 5 4
  3. C. 0 3 2 7 6 1 4 5
  4. D. 0 1 6 5 3 4 7 2

Correct answer: C. 0 3 2 7 6 1 4 5

Recursive DFS gives 0 3 2 7 6 1 4 5. Using an explicit stack that marks vertices on pop, with neighbours pushed in list order, gives 0 1 6 7 2 3 5 4 because the last neighbour is explored first. BFS gives 0 3 5 6 1 2 4 7.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic