algorithmtime-complexitytowers-of-hanoi

Towers of Hanoi with two auxilary rods


I came across this problem on one of the websites.

Requirement:

Need to propose the algorithm and caclulate the time complexity of Towers of Hanoi problem if two auxilary rods are given instead of one.

My Attempt:

Original Towers of Hanoi:

T(N)= T(N-1) // Moving N-1 disks from Source to Auxilary 
    + 1      // Moving Nth disk from Source to Destination  
    + T(N-1) // Moving N-1 disks from Auxilary to Destination

     T(N) = 2*T(N-1) + 1 

            = O(2 power N )   // exponential.

In the current problem since we have two auxialry rods

`

     T(N) =

          T(N/2)  // Moving top N/2 from Source to Aux1

          + T(N/2)  // Moving the remaining N/2 from Source to Destination using Aux2.

           + T(N/2)  // Moving N/2 from Aux1 to Destination.

                T(N) = 3*T(N/2) 
                =O( 3 power log N base 2 ) 
                = O( N power log 3 base 2 )  // less than quadartic.

But I am not very sure about this since I am not calculation time as T(N/2) for moving top N/2 to Aux1 and also for moving botton N/2 from Source to Destination using Aux2.

Why I think it is incorrect is because in first case while moving top (N/2) we can play with three rods : Destiation,Aux1 & Aux2 But while moving the bottom (N/2) we can play only with two rods Destination,Aux2

So I think there should even better approach for this problem.


Solution

  • Here's a simple memoized recursive function in Python that uses the Frame–Stewart algorithm to find the minimum number of moves. According to the Wikipedia article linked above, this algorithm is proven to be optimal for 4 pegs and up to 30 disks, and it's believed to be optimal for all combinations of n disks and r pegs (but not proven to be so). Its possible my implementation could be optimized a bit, but it's fast enough for reasonable n and r values.

    def hanoi(n, r, memo={}):    # deliberately using a mutable default argument here
        """Return the number of steps required to move n disks using a total of r pegs."""
        if n == 1:               # base case
            return 1
        if r <= 2:               # impossible cases
            return float("inf")
        if (n,r) not in memo:
            memo[n, r] = min(hanoi(k, r)*2 + hanoi(n-k, r-1)   # recursive calls
                             for k in range(1, n))
        return memo[n, r]