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'])- A. ACBED 7
- B. ABCDE 8
- C. ACBDE 7
- 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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Prim's algorithm from vertex 0 on the undirected graph below. In what order are vertices added and what is the MST weight? python import…
- Kahn's topological sort with a FIFO queue (initial zero-indegree vertices in increasing order). What is printed? python from collections…
- Kruskal's algorithm: which edges are accepted, in order, for the graph below? python edges = sorted([(7, 'A', 'B'), (5, 'A', 'D'), (8…
- How many times is the base case reached when computing C(5, 2) with the plain recursion C(n, k) = C(n−1, k−1) + C(n−1, k)? python base = 0…
- What is printed? (Tower of Hanoi: number of moves and the 5th move) python moves = [] def hanoi(n, a, b, c): if n == 0: return hanoi(n…
- What is printed? (recursion output order) python out = [] def f(n): if n == 0: return out.append(n) f(n - 1) out.append(n) f(3) print(out)