Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Towers of Hanoi puzzleΒΆ

A classic puzzle: given a board with three pegs, move a stack of disks of different size from the left-most peg to the right-most peg, moving one disk at a time and following the rule that no larger disk can be placed on top of a smaller one.

Towers of Hanoi

A surprisingly powerful technique in scientific programming β€” and the structure of every dynamic programming solver we write later in the course.

The Hanoi puzzle can be solved nicely by breaking it into small parts using the following algorithm:

def move(from,to):
  move one disk from --> to

def main_algorithm(n,source,aux,target):
  '''
  Inputs: number of disks n
        source peg
        auxiliary peg
        target peg
  '''
  if n==0:
    do nothing, return
  if n==1:
    move(source,target)
  if n>0:
    main_algorithm(n-1,source,target,aux)
    move(source,target)
    main_algorithm(n-1,aux,source,target)

The solution for nn disks requires 2nβˆ’12^n-1 moves, so 15 for the four disks below β€” the illustration stops at configuration 13, two moves short of the goal.

Source
Loading...