Data Structures & AlgorithmsModerateTCS NQT · graph warm-up

Problem: Count the connected components of the undirected graph on 6 vertices with edges (0,1), (1,2), (3,4), (5,5) using DFS. Run the code.

Problem: Count the connected components of the undirected graph on 6 vertices with edges (0,1), (1,2), (3,4), (5,5) using DFS. Run the code.
g = {i: [] for i in range(6)}
for u, v in [(0, 1), (1, 2), (3, 4), (5, 5)]:
    g[u].append(v)
    g[v].append(u)
seen = set()
comp = 0
def dfs(u):
    seen.add(u)
    for v in g[u]:
        if v not in seen:
            dfs(v)
for i in range(6):
    if i not in seen:
        comp += 1
        dfs(i)
print(comp)
What is printed?
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. 6

Correct answer: B. 3

The components are {0,1,2}, {3,4} and {5}, so there are 3. The self-loop (5,5) does not join anything, and forgetting the isolated vertex 5 gives 2.

More Coding Interview Problems questions

Exams that ask this topic