The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods and a number
of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a
neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical
shape. The objective of the puzzle is to move the entire stack to another rod, obeying the
following simple rules:
• Only one disk can be moved at a time.
• Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack.
• No disk may be placed on top of a smaller disk.
Design an iterative and recursive algorithm for above mathematical game.
Algorithm
1- Compute the required number of moves by using pow(2,n),
where n is the total number of moves. This means that square the number of disks
to find the total number of moves.
2- When the disks number is even, interchage the auxiliary stack
and the destination stack.
3- for x = 1 to moves number:
if(x % 3) == 1:
there should be a legal move of disk's top between the source and destination stacks.
else if (x % 3) ==2:
Indicates a legal move of disk's top between source stack and the auxiliary stack
else if (x%3) ==0:
Indicates a legal move of disk's top between auxiliary stack and the destination stack
Comments
Leave a comment