Towers of Hanoi

From Rosetta Code
Revision as of 15:28, 25 January 2007 by 151.38.77.14 (talk)
Task
Towers of Hanoi
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the goal is to solve the Towers of Hanoi problem with recursivity.

Python

def hanoi(ndisks, startPeg=1, endPeg=3):
  if ndisks:
    hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
    print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg)
    hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)

hanoi(ndisks=4)