ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
// undirected graph; neighbours are visited in increasing order
Edges: 1-2, 1-3, 2-4, 3-4, 4-5, 3-6, 6-7, 5-7
Procedure dfs(Integer u)
    mark u visited
    Print u
    for (each neighbour v of u, in increasing order)
        if (v not visited) dfs(v)
    end for
End Procedure
dfs(1)
  1. A. 1 2 3 4 6 5 7
  2. B. 1 2 4 3 6 7 5
  3. C. 1 2 4 5 7 6 3
  4. D. 1 3 6 7 5 4 2

Correct answer: B. 1 2 4 3 6 7 5

Depth-first search follows the smallest unvisited neighbour as far as possible: 1 → 2 → 4 → 3 → 6 → 7 → 5. At 4 the smallest unvisited neighbour is 3 (not 5), which is the usual trap. Output 1 2 4 3 6 7 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic