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)- A. 1 2 3 4 6 5 7
- B. 1 2 4 3 6 7 5
- C. 1 2 4 5 7 6 3
- 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.
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? 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…
- What will be the output of the following pseudocode? ((mask >> i) & 1 is evaluated before ==; ^ is XOR) Integer a[3] = {5, 1, 6}, total =…