Data Structures & AlgorithmsVery hardGATE CS 2 marks · Codeforces Div 2 B
Undirected graph on vertices 0 to 7 with edges listed as: 2–5, 1–2, 3–5, 1–4, 0–1, 0–2, 2–4, 6–7, 5–6, 0–3, 0–5, 3–7. 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)?
- A. 0 1 2 5 3 7 6 4
- B. 0 1 2 3 5 4 7 6
- C. 0 5 6 7 3 2 4 1
- D. 0 5 3 2 1 6 7 4
Correct answer: A. 0 1 2 5 3 7 6 4
Recursive DFS gives 0 1 2 5 3 7 6 4. Using an explicit stack that marks vertices on pop, with neighbours pushed in list order, gives 0 5 6 7 3 2 4 1 because the last neighbour is explored first. BFS gives 0 1 2 3 5 4 7 6.
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
- Undirected graph on vertices 0 to 5 with edges listed as: 3–4, 1–4, 1–3, 2–4, 2–3, 4–5, 0–5, 0–4. The adjacency list of each vertex is…
- Directed graph on vertices 0 to 5 with positive weights (u→v (w)): 2→1 (2), 2→4 (4), 1→3 (3), 1→2 (3), 3→4 (4), 4→5 (1), 0→3 (1), 1→4 (1)…
- Directed graph on vertices 0 to 6 with positive weights (u→v (w)): 3→4 (1), 6→5 (4), 4→3 (2), 4→6 (3), 3→6 (4), 1→3 (3), 3→2 (2), 5→1 (3)…
- Directed graph on vertices 0 to 5 with positive weights (u→v (w)): 5→2 (3), 2→5 (3), 5→1 (4), 5→3 (1), 3→2 (2), 1→3 (2), 4→5 (2), 0→3 (4)…
- Directed graph on vertices 0 to 6 with positive weights (u→v (w)): 4→5 (1), 2→6 (1), 4→0 (1), 5→3 (4), 4→6 (2), 4→3 (4), 6→0 (1), 0→5 (4)…
- Directed graph on vertices 0 to 4 with positive weights (u→v (w)): 4→1 (1), 1→4 (4), 4→3 (1), 3→2 (3), 3→4 (2), 4→2 (4), 4→0 (2), 1→3 (2)…