1

Hi I am trying to create an iterative solution for Tower of Hanoi. However I cannot figure out how to incorporate the movement of the disk. For example in following function call for 2 disks, I want to return output as :

Move disk 1 from A to B, Move disk 2 from A to C, Move disk 1 from B to C

Here is what I have so far

import time
#Iterative solution Tower of Hanoi 

start = time.time()

def iterative_hanoi(n):
legalmoves = []
number_of_moves = 2**n-1
source_peg = 'A'
auxiliary_peg = 'B'
destination_peg = 'C'
i = 0
if n % 2==0:
    destination_peg = 'B'
    auxiliary_peg = 'C'

while i in range(0,number_of_moves):
    i +=1
    if i%3 == 1:
        legalmoves.append(source_peg + destination_peg)
    if i%3 == 2:
        legalmoves.append(source_peg + auxiliary_peg)
    if i%3 == 0:
        legalmoves.append(auxiliary_peg + destination_peg)

return legalmoves

print(iterative_hanoi(2))

end = time.time()
print(end - start)

1 Answers1

2

When a problem has both recursive and iterative solutions, the recursive solution is usually easier to formulate and understand. The iterative solution is often more efficient, but requires a deeper insight.

Here's a different way to understand how the disks move in a Towers of Hanoi solution, that makes it easy to write an iterative solution:

Arrange the pegs in a triangle like this:

     A     C

        B

Now, each time you move a disk, it's going to move either clockwise or counter-clockwise.

RULE 1: A single disk will move in only one direction -- clockwise or counter-clockwise.

RULE 2: Alternate disks move in opposite directions.

That means that if disk 1 (the smallest) moves clockwise, then 1, 3, 5, 7... all move clockwise, and 2, 4, 6, 8, ... all move counter-clockwise.

It also means that if the you have an even number of disks, then the largest and smallest move in opposite directions. Otherwise they move in the same direction. This makes it easy to figure out which way the first move goes. You want the largest disk to move only once, so that one determines the direction of all the other disks.

RULE 3: Always move the biggest disk you can, in its proper direction.

Rule 3 determines the pattern of which disk moves. It's 1, 2, 1, 3, 1, 2, 1, ... You start with all 1s, and replace every 2nd 1 with a 2. Then replace every 2nd 2 with a 3, etc. If you count in binary with a bit for each disk: 000 001 010 011 100... then at each step, the highest bit that changes corresponds to the largest disk that moves. If you start at all 0s, then you're done when you get to all 1s.


Using these rules, it's easy to write an iterative solution. First, use rules 1 and 2 to figure out which direction every disk moves in. Then use rule 3 at every iteration to figure out which disk to move.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87