Data Structures & AlgorithmsVery hardProduct company OA
BFS that also counts the number of shortest paths. What is printed (dist[7], ways[7], ways[6], ways[4])?
BFS that also counts the number of shortest paths. What is printed (dist[7], ways[7], ways[6], ways[4])?
from collections import deque
adj = {0: [1, 2, 3], 1: [4], 2: [4, 5], 3: [5], 4: [6], 5: [6], 6: [7], 7: []}
dist = {0: 0}; ways = {0: 1}; q = deque([0])
while q:
u = q.popleft()
for v in adj[u]:
if v not in dist:
dist[v] = dist[u] + 1; ways[v] = ways[u]; q.append(v)
elif dist[v] == dist[u] + 1:
ways[v] += ways[u]
print(dist[7], ways[7], ways[6], ways[4])- A. 4 6 4 2
- B. 4 4 4 2
- C. 4 4 6 2
- D. 4 2 2 1
Correct answer: B. 4 4 4 2
When v is first discovered it inherits ways[u]; every later u' at distance dist[v] − 1 adds its ways too (BFS guarantees all such u' are processed before v is). 4 gets paths via 1 and 2 → 2; 5 via 2 and 3 → 2; 6 = 2 + 2 = 4; 7 inherits 4. Distances: 0 → {1, 2, 3} → {4, 5} → 6 → 7, so dist 4. Adding ways only at discovery would give 1 for every vertex. O(V + E).
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
- Dijkstra with a binary heap and lazy deletion (no decrease-key; outdated entries are skipped when popped). What is printed (dist to E…
- AVL insertions (rotations labelled by imbalance case). What is printed (preorder, rotation cases in order, height in edges)? python class…
- B-tree with minimum degree t = 2 (a 2-3-4 tree, at most 3 keys per node) using the single-pass insertion that splits every FULL node on…
- Building a min-heap from [9, 8, 7, 6, 5, 4, 3]: (a) seven sift-up insertions, (b) bottom-up heapify. What is printed (heaps and swap…
- Exact count of the innermost statement for n = 30 (j advances by i, k advances by j). What is printed? python c = 0 n = 30 for i in…
- A memoised recursion f(n) = f(n//2) + f(n//3) + f(n//6) is evaluated for n = 10¹². How many distinct calls (cache misses) are made? python…