Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

Run Dijkstra from A on the weighted directed graph. In what order are vertices finalised (popped), and what is dist[E]?

Run Dijkstra from A on the weighted directed graph. In what order are vertices finalised (popped), and what is dist[E]?
import heapq
g = {'A': [('B', 4), ('C', 1)], 'B': [('E', 4)], 'C': [('B', 2), ('D', 5)], 'D': [('E', 1)], 'E': []}
dist = {v: float('inf') for v in g}; dist['A'] = 0
pq, order = [(0, 'A')], []
while pq:
    d, u = heapq.heappop(pq)
    if d > dist[u]: continue
    order.append(u)
    for v, w in g[u]:
        if d + w < dist[v]: dist[v] = d + w; heapq.heappush(pq, (dist[v], v))
print(''.join(order), dist['E'])
  1. A. ACBED 7
  2. B. ABCDE 8
  3. C. ACBDE 7
  4. D. ACBDE 8

Correct answer: C. ACBDE 7

A (0) → C (1) → B via C (3, better than 4) → D (6) and E via B (7) – D is popped first at 6, then E at 7 (the path through D also gives 7). Picking the nearest unvisited vertex each time is what makes Dijkstra correct for non-negative weights.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic