Data Structures & AlgorithmsModerateTCS NQT · BFS warm-up

Problem: What is the length of the shortest path from node 1 to node 5 in the undirected graph with edges (1,2), (2,3), (1,4), (4,5), (3,5)? Run the BFS.

Problem: What is the length of the shortest path from node 1 to node 5 in the undirected graph with edges (1,2), (2,3), (1,4), (4,5), (3,5)? Run the BFS.
from collections import deque
g = {i: [] for i in range(1, 6)}
for u, v in [(1, 2), (2, 3), (1, 4), (4, 5), (3, 5)]:
    g[u].append(v)
    g[v].append(u)
dist = {1: 0}
q = deque([1])
while q:
    u = q.popleft()
    for v in g[u]:
        if v not in dist:
            dist[v] = dist[u] + 1
            q.append(v)
print(dist[5])
What is printed?
  1. A. 3
  2. B. 1
  3. C. 4
  4. D. 2

Correct answer: D. 2

The path 1-4-5 has 2 edges, shorter than 1-2-3-5 with 3 edges. BFS finds the minimum edge count.

More Coding Interview Problems questions

Exams that ask this topic