TowerOfHanoi Program
Description
The Tower of Hanoi puzzle consists of three rods, and a number of disks of different sizes which can stack onto any rod.The puzzle starts with a stack of disks in ascending order in size on the 1st rod (the smallest disk at the top).
The goal is to move the entire stack to the 3rd rod with the following rules:
(The 2nd rod is an intermediate rod to help to solve the puzzle.)
1. Only one disk may be moved at a time.
2. Each move consists of taking the top most disk from one of the stacks and placing it on top of another stack.
3. The larger disk cannot be placed on top of a smaller disk.
1. Only one disk may be moved at a time.
2. Each move consists of taking the top most disk from one of the stacks and placing it on top of another stack.
3. The larger disk cannot be placed on top of a smaller disk.
Associated Concepts:
Recursion
Algorithm:
main method:
Declare variables
Input one integer: n (the number of disks)
Call the recursive method move() with n, tower1, tower3, and tower2 as the arguments
move method definition:
Declare variables
Input one integer: n (the number of disks)
Call the recursive method move() with n, tower1, tower3, and tower2 as the arguments
move method definition:
If the method is call with the base case: n is 1,
it prints the message of moving one disk from the source tower to the
target tower.
Otherwise, the method breaks down into 3 steps:
Otherwise, the method breaks down into 3 steps:
1. Call the move() method to move n - 1 disks from tower1 to tower2 using
tower3 as the intermediate rod.
2. Print the message of moving one disk from the source tower to the target tower.
3. Call the move() method to move n - 1 disks from tower2 to tower3 using tower1 as the intermediate rod.
2. Print the message of moving one disk from the source tower to the target tower.
3. Call the move() method to move n - 1 disks from tower2 to tower3 using tower1 as the intermediate rod.