Question DSA-GRAPH-0012
MediumWhat is the output of this code?
import heapq
g = {0: [(1, 4), (2, 1)], 1: [(3, 1)], 2: [(1, 2), (3, 5)], 3: []}
dist = {0: 0}
pq = [(0, 0)]
while pq:
d, u = heapq.heappop(pq)
if d > dist.get(u, float('inf')):
continue
for v, w in g[u]:
if d + w < dist.get(v, float('inf')):
dist[v] = d + w
heapq.heappush(pq, (d + w, v))
print(dict(sorted(dist.items())))
- A.
{0: 0, 1: 3, 2: 1, 3: 6}
- B.
{0: 0, 1: 2, 2: 1, 3: 3}
- C.
{0: 0, 1: 4, 2: 1, 3: 5}
- D.
{0: 0, 1: 3, 2: 1, 3: 4}
Sign up free to see the answer and a step-by-step explanation.