ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
from collections import deque
def zero_one(n, edges, src):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
        adj[v].append((u, w))
    INF = float('inf')
    d = [INF] * n
    d[src] = 0
    dq = deque([src])
    while dq:
        u = dq.popleft()
        for v, w in adj[u]:
            if d[u] + w < d[v]:
                d[v] = d[u] + w
                if w == 0:
                    dq.appendleft(v)
                else:
                    dq.append(v)
    return d
print(zero_one(4, [(0, 1, 0), (1, 2, 1), (0, 2, 1), (2, 3, 0)], 0))
  1. A. [0, 1, 1, 1]
  2. B. [0, 0, 1, 2]
  3. C. [0, 0, 0, 1]
  4. D. [0, 0, 1, 1]

Correct answer: D. [0, 0, 1, 1]

Weight-0 edges push to the front of the deque and weight-1 edges to the back, so the deque stays ordered by distance. Vertices 1 and 3 are reached through weight-0 edges, while vertex 2 costs 1.

More Python Programming questions

Exams that ask this topic