Tuesday, December 25, 2012

Java Exercise #98: Towers of Hanoi (Recursion)

Towers of Hanoi is a classic recursion problem. The problem involves moving a specified number of disks of distinct sizes from one tower to another while observing the following rules.

    • There are n disks labeled 1,2,3...n and three towers labeled A, B and C.
      No disk can be on top of a smaller disk at any time.
      All the disks are initially placed on tower A.
      Only one disk can be moved at a time and it must be the top disk on the tower.
  • The objectve of the problem is to move all the disks from A to B with the assistance of C.

    Exercise: Use recursion to write a program that will take user input for number of disks and solve the problem for that number of disks.

    
    Enter the number of disks:3
    The moves are:
    Move disk 1 from A to B
    Move disk 2 from A to C
    Move disk 1 from B to C
    Move disk 3 from A to B
    Move disk 1 from C to A
    Move disk 2 from C to B
    Move disk 1 from A to B
    
    
    
    

    Download Code: Towers of Hanoi

    No comments:

    Post a Comment