Data Structures & AlgorithmsModerateTCS NQT · Accenture pattern

An undirected graph has edges A–B, A–C, B–D, C–D, C–E, D–F, E–G, F–G, G–H. How many vertices are at a shortest distance of EXACTLY 2 edges from A?

  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 1

Correct answer: B. 2

BFS from A: level 1 = B, C; level 2 = D (from B or C) and E (from C); level 3 = F, G; level 4 = H. So exactly 2 vertices (D and E). Counting D twice, once via B and once via C, gives 3 – BFS marks a vertex when it is first discovered.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic