Skip to main content

TOH problem with solution for n disks

Short answer

Move n disks from source to destination using auxiliary with one disk per move and no larger on smaller. Solve recursively: move n-1 disks to auxiliary, move largest to destination, then move n-1 from auxiliary. The number of moves is 2^n - 1.

Explain TOH problem with its solution for n disks.

The problem

Tower of Hanoi has three pegs (source A, auxiliary B, destination C) and n disks of different sizes stacked on A with the largest at the bottom. Move all disks to C under these rules:

  1. Only one disk is moved at a time.
  2. Only the top disk of a peg can be moved.
  3. A larger disk may never be placed on a smaller one.

Recursive solution for n disks

To move n disks from A to C using B:

  1. Move the top n-1 disks from A to B (using C as auxiliary).
  2. Move the largest disk n from A to C.
  3. Move the n-1 disks from B to C (using A as auxiliary).

Base case: one disk is moved directly. The same idea solves the smaller problems, so it is naturally recursive.

void toh(int n, char from, char to, char aux) {
    if (n == 1) { printf("Move disk 1 from %c to %c\n", from, to); return; }
    toh(n - 1, from, aux, to);
    printf("Move disk %d from %c to %c\n", n, from, to);
    toh(n - 1, aux, to, from);
}

Number of moves

T(1) = 1 and T(n) = 2T(n-1) + 1, which gives T(n) = 2ⁿ − 1. Time complexity is O(2ⁿ).

n12345
moves1371531

Example n = 3 (A to C)

MoveDiskFromToPegs after the move (A / B / C)
11AC3,2 / - / 1
22AB3 / 2 / 1
31CB3 / 2,1 / -
43AC- / 2,1 / 3
51BA1 / 2 / 3
62BC1 / - / 3,2
71AC- / - / 3,2,1

Total 7 = 2³ − 1 moves (generated and checked with a program).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 5 questions →