Data Structures & AlgorithmsModerateWipro · Accenture pattern

What is printed? (Tower of Hanoi: number of moves and the 5th move)

What is printed? (Tower of Hanoi: number of moves and the 5th move)
moves = []
def hanoi(n, a, b, c):
    if n == 0: return
    hanoi(n - 1, a, c, b); moves.append(a + c); hanoi(n - 1, b, a, c)
hanoi(3, 'A', 'B', 'C')
print(len(moves), moves[4])
  1. A. 7 AC
  2. B. 7 BA
  3. C. 8 BA
  4. D. 7 BC

Correct answer: B. 7 BA

T(n) = 2T(n − 1) + 1 = 2ⁿ − 1 = 7 moves. The sequence for 3 discs from A to C is AC, AB, CB, AC, BA, BC, AC – the 5th move is B → A. The middle (4th) move is always the largest disc A → C.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic