Tower of Hanoi Problem- Recursion Variations and Solutions

What Is the Tower of Hanoi Problem?

The Tower of Hanoi is a classic puzzle with three pegs and a stack of disks of different sizes. You start with all disks on one peg in descending size order (largest at the bottom). The goal is to move the entire stack to another peg, following two rules:

It sounds simple. It isn't. The minimum number of moves required follows the formula 2ⁿ - 1, where n is the number of disks. For 3 disks, that's 7 moves. For 10 disks, that's 1,023 moves. The complexity grows exponentially.

The Recursive Solution

Recursion is the natural way to solve this. The algorithm breaks the problem into three steps:

  1. Move n-1 disks from source to auxiliary peg
  2. Move the largest disk from source to destination
  3. Move n-1 disks from auxiliary to destination

Here's the implementation in Python:


def tower_of_hanoi(n, source='A', destination='C', auxiliary='B'):
    if n == 1:
        print(f"Move disk 1 from {source} to {destination}")
        return
    tower_of_hanoi(n-1, source, auxiliary, destination)
    print(f"Move disk {n} from {source} to {destination}")
    tower_of_hanoi(n-1, auxiliary, destination, source)

# Example: 3 disks
tower_of_hanoi(3)

The output shows the exact sequence of moves. For 3 disks, you get 7 moves. Each recursive call handles a smaller subproblem until you reach the base case of a single disk.

Understanding the Move Count

The recurrence relation is straightforward: T(n) = 2T(n-1) + 1. Solving this gives you 2ⁿ - 1. This isn't approximate—it's the absolute minimum possible moves.

Move Counts by Disk Number

Disks (n)Minimum Moves (2ⁿ - 1)
11
23
37
415
531
663
7127
101,023
201,048,575

Notice the pattern. Each additional disk doubles the work and adds one more move. That's the nature of exponential growth—things get out of hand fast.

Non-Recursive Approaches

Recursion works, but it creates n stack frames. For large n, you can hit stack overflow limits. Here's an iterative version using a bit-manipulation trick:


def tower_of_hanoi_iterative(n):
    total_moves = 2 ** n - 1
    for move in range(1, total_moves + 1):
        # Determine which disk to move
        from_peg = (move & move - 1) % 3
        to_peg = ((move | move - 1) + 1) % 3
        
        # Convert to peg labels
        pegs = ['A', 'B', 'C']
        print(f"Move disk from {pegs[from_peg]} to {pegs[to_peg]}")

This version uses the binary representation of move numbers to determine which disk moves and where. Same result, no recursion stack.

Common Variations

1. Four Pegs (Reve's Puzzle)

The classic problem uses 3 pegs. Add a fourth peg and the problem gets harder. The optimal solution is no longer simply recursive. Frame-Stewart's algorithm gives the best-known solution, though it wasn't proven optimal for all cases until recently.

For 4 pegs and n disks, the Frame-Stewart approach works like this:

Finding the optimal k is non-trivial. There's no closed-form formula.

2. Limited Moves

What if you have a fixed move budget? Can you determine if a solution exists within m moves? This becomes a decision problem. You can solve it by checking if m falls on the sequence of optimal move counts.

3. Adjacent Pegs Only

Standard rules allow moving between any two pegs. Some variations restrict you to moving only to adjacent pegs. This adds a layer of complexity—you need to account for the physical distance traveled, not just the logical moves.

4. Colored or Restricted Disks

Some disks might have restrictions on which pegs they can occupy. Or you might have multiple disks of the same size that need special handling. These constraints break the standard recursive solution and require custom state-tracking.

Getting Started: Implementing Your Own Solver

Start with the 3-disk recursive solution. Get that working first. Then extend it:

  1. Parameterize the number of disks
  2. Add move counting to verify you're hitting 2ⁿ - 1
  3. Convert to an iterative version once you understand the pattern
  4. Try the 4-peg version with Frame-Stewart

Don't skip steps. The iterative version only makes sense after you've built the recursive version and understand why each move happens.

Applications Beyond Puzzles

The Tower of Hanoi isn't just academic. It models real problems:

Any situation where you need to move items between locations while respecting size/order constraints can map to this problem.

Comparison: Recursive vs Iterative

AspectRecursiveIterative
Code claritySimple, mirrors problem structureHarder to read, requires understanding the bit trick
Memory usageO(n) stack framesO(1)
Stack overflow riskYes, for large nNo
SpeedSameSame
ExtensibilityEasy to modify rulesHarder to adapt

Use recursion for clarity and quick implementation. Use iteration when memory matters or when you're working with embedded systems with limited stack space.

The Bottom Line

The Tower of Hanoi teaches you three things that matter in real code:

Build the recursive solution first. Understand why it works. Then optimize if you need to. Most programmers never need to solve this in production—but the thinking patterns transfer directly to any recursive problem you'll encounter.