Data Structures & AlgorithmsModerateTCS NQT · graph warm-up

Problem: How many nodes are reachable from 0 in the directed graph with edges 0->1, 1->2, 3->0? Run the DFS code.

Problem: How many nodes are reachable from 0 in the directed graph with edges 0->1, 1->2, 3->0? Run the DFS code.
g = {0: [1], 1: [2], 2: [], 3: [0]}
seen = set()
def dfs(u):
    seen.add(u)
    for v in g[u]:
        if v not in seen:
            dfs(v)
dfs(0)
print(len(seen))
What is printed?
  1. A. 4
  2. B. 2
  3. C. 3
  4. D. 1

Correct answer: C. 3

From 0 the walk reaches 1 and then 2, so {0,1,2} is reachable. The edge 3->0 points into 0, not out of it.

More Coding Interview Problems questions

Exams that ask this topic