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- A. 1 2 4 3 6 5 7
- B. 1 2 3 4 6 5 7
- C. 1 2 3 4 5 6 7
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? // undirected graph; neighbours are visited in increasing order Edges: 1-2, 1-3, 2-4…
- What will be the output of the following pseudocode? Integer parent[1..8] for (each i from 1 to 8) parent[i] = i Function find(Integer x)…
- What will be the output of the following pseudocode? // directed graph with edge weights Edges: A->B 4, A->C 1, C->B 2, B->D 1, C->D 5…
- What will be the output of the following pseudocode? // directed edges: 5->2, 5->0, 4->0, 4->1, 2->3, 3->1 Compute indegree of every…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 0, digitsA = 0…
- What will be the output of the following pseudocode? Function odd(Integer n) if (n == 0) return 0 end if return odd(n - 1) + 2 n - 1 End…