🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Shortest Paths: all 10 questions

Quiz: Shortest Paths · Question 2 of 10

What does this print? (code)

What does this print?

import heapq
adj = {0: [(1, 5), (2, 1)], 1: [(3, 1)], 2: [(1, 1), (3, 6)], 3: []}
dist = {0: 0, 1: 99, 2: 99, 3: 99}
pq = [(0, 0)]
while pq:
    d, u = heapq.heappop(pq)
    if d > dist[u]:
        continue
    for v, w in adj[u]:
        if d + w < dist[v]:
            dist[v] = d + w
            heapq.heappush(pq, (dist[v], v))
print(dist[1], dist[3])
  1. A.5 6
  2. B.2 7
  3. C.5 7
  4. D.2 3
Answer & explanation

Correct answer: 2 3

0 → 2 → 1 costs 1 + 1 = 2, and 0 → 2 → 1 → 3 costs 3, better than 0 → 2 → 3 = 7.

Can you get the rest right without peeking?

Take the timed Quiz: Shortest Paths quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →