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])
  1. A. 4 6 4 2
  2. B. 4 4 4 2
  3. C. 4 4 6 2
  4. 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).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic