Data Structures & AlgorithmsModerateTCS NQT Digital · Accenture

Problem: Vertices 0–5 form a graph with edges 0-1, 1-2, 2-3, 3-0 and 4-5. A BFS from vertex 0 gives each vertex a distance. What is the sum of these distances over the vertices that are reachable from 0?

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

Correct answer: A. 4

BFS distances are 0 for the source, 1 for vertices 1 and 3, and 2 for vertex 2, totalling 0+1+1+2 = 4. Vertices 4 and 5 are unreachable and excluded.

More Coding Interview Problems questions

Exams that ask this topic