Data Structures & AlgorithmsVery hardICPC regional · backtracking

Problem: How many simple paths go from 0 to 3 in the undirected graph with edges 0-1, 1-2, 2-3, 3-0 and the chord 0-2? Run the DFS code.

Problem: How many simple paths go from 0 to 3 in the undirected graph with edges 0-1, 1-2, 2-3, 3-0 and the chord 0-2? Run the DFS code.
g = {0: [1, 3, 2], 1: [0, 2], 2: [1, 3, 0], 3: [2, 0]}
def count(u, t, seen):
    if u == t:
        return 1
    total = 0
    for v in g[u]:
        if v not in seen:
            seen.add(v)
            total += count(v, t, seen)
            seen.remove(v)
    return total
print(count(0, 3, {0}))
What is printed?
  1. A. 4
  2. B. 3
  3. C. 2
  4. D. 6

Correct answer: B. 3

The simple paths from 0 to 3 are 0-3, 0-2-3 and 0-1-2-3. Backtracking removes each visited vertex so no path repeats a vertex.

More Coding Interview Problems questions

Exams that ask this topic