ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (breadth-first traversal using a queue)?

What will be the output of the following pseudocode (breadth-first traversal using a queue)?
Map graph = {0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2]}
Boolean visited[4] = all false
List order = empty list
Queue q = empty queue
enqueue(q, 0)
visited[0] = true
while (not isEmpty(q))
    Integer u = dequeue(q)
    append(order, u)
    for (each v in graph[u])
        if (not visited[v])
            visited[v] = true
            enqueue(q, v)
        end if
    end for
end while
Print order
  1. A. [0, 1, 2, 3]
  2. B. [0, 2, 1, 3]
  3. C. [0, 1, 3, 2]
  4. D. [0, 3, 1, 2]

Correct answer: A. [0, 1, 2, 3]

BFS visits 0 first, enqueues its neighbors 1 and 2 in that order, then dequeues and visits 1 (enqueuing its unvisited neighbor 3), then visits 2 (3 already enqueued/visited), then finally 3: [0, 1, 2, 3].

More Pseudocode and Code Tracing questions

Exams that ask this topic