Iterative Tower of Hanoi
The Tower of Hanoi is a mathematical puzzle. It consists of three poles and a number of disks of different sizes which can slide onto any pole. The puzzle starts with the disk in a neat stack in ascending order of size in one pole, the smallest at the top thus making a conical shape. The objective of the puzzle is to move all the disks from one pole (say ‘source pole’) to another pole (say ‘destination pole’) with the help of the third pole (say auxiliary pole).
The puzzle has the following two rules:
1. You can’t place a larger disk onto a smaller disk
2. Only one disk can be moved at a time
We’ve already discussed a recursive solution for the Tower of Hanoi. We have also seen that for n disks, a total of 2n – 1 moves are required.
1. Calculate the total number of moves required i.e. "pow(2, n) - 1" here n is number of disks. 2. If number of disks (i.e. n) is even then interchange destination pole and auxiliary pole. 3. for i = 1 to total number of moves: if i%3 == 1: legal movement of top disk between source pole and destination pole if i%3 == 2: legal movement top disk between source pole and auxiliary pole if i%3 == 0: legal movement top disk between auxiliary pole and destination pole
Let us understand with a simple example with 3 disks: So, total number of moves required = 7
S A D When i= 1, (i % 3 == 1) legal movement between‘S’ and ‘D’
When i = 2, (i % 3 == 2) legal movement between ‘S’ and ‘A’
When i = 3, (i % 3 == 0) legal movement between ‘A’ and ‘D’ ’
When i = 4, (i % 3 == 1) legal movement between ‘S’ and ‘D’
When i = 5, (i % 3 == 2) legal movement between ‘S’ and ‘A’
When i = 6, (i % 3 == 0) legal movement between ‘A’ and ‘D’
When i = 7, (i % 3 == 1) legal movement between ‘S’ and ‘D’
So, after all these destination poles contains all the in order of size.
After observing above iterations, we can think that after a disk other than the smallest disk is moved, the next disk to be moved must be the smallest disk because it is the top disk resting on the spare pole and there are no other choices to move a disk.
Tower of Hanoi for 3 disks: Move disk 1 from rod S to rod D Move disk 2 from rod S to rod A Move disk 1 from rod D to rod A Move disk 3 from rod S to rod D Move disk 1 from rod A to rod S Move disk 2 from rod A to rod D Move disk 1 from rod S to rod D
Time Complexity: O(2ᴺ) Since the iterative solution needs to generate and process all possible combinations of moves for n disks, the number of iterations grows exponentially with the number of disks.
Auxiliary Space: O(n)
This article is contributed by Anand Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Please Login to comment...