ProgrammingHardGATE CS & IT · Infosys

What is printed?

What is printed?
from collections import deque
g = {1: [2, 3], 2: [4], 3: [4, 5], 4: [6], 5: [], 6: []}
dist = {1: 0}
q = deque([1])
while q:
    u = q.popleft()
    for v in g[u]:
        if v not in dist:
            dist[v] = dist[u] + 1
            q.append(v)
print(sorted(v for v in dist if dist[v] == 2))
  1. A. [4, 5]
  2. B. [4, 5, 6]
  3. C. [2, 3]
  4. D. [4]

Correct answer: A. [4, 5]

Vertices at distance 2 are reached through distance-1 vertices 2 or 3, which gives 4 and 5. Vertex 6 is at distance 3 because it is reached through 4.

More Python Programming questions

Exams that ask this topic