ProgrammingHardAmazon 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
Queue q = {1}
mark 1 visited
while (q not empty)
    Integer u = dequeue(q)
    Print u
    for (each neighbour v of u, in increasing order)
        if (v not visited)
            mark v visited
            enqueue(q, v)
        end if
    end for
end while
  1. A. 1 2 4 3 6 5 7
  2. B. 1 2 3 4 6 5 7
  3. C. 1 2 3 4 5 6 7
  4. D. 1 3 2 4 6 5 7

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

Breadth-first search goes level by level: 1; then its neighbours 2, 3; then 4 (from 2) and 6 (from 3); then 5 (from 4) and 7 (from 6). Output 1 2 3 4 6 5 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic