Skip to content
Related Articles

Related Articles

Tower of Hanoi | Set 2
  • Last Updated : 04 May, 2021

Given a positive integer N representing the number of disks in the Tower of Hanoi, the task is to solve the Tower of Hanoi puzzle using Binary representations.

Examples:

Input: N = 3
Output:
Move the 1 disk to next circular right rod
Move the 2 disk to next circular right rod
Move the 1 disk to next circular right rod
Move the 3 disk to next circular right rod
Move the 1 disk to next circular right rod
Move the 2 disk to next circular right rod
Move the 1 disk to next circular right rod

Input: N = 4
Output:
Move the 1 disk to next circular right rod
Move the 2 disk to next circular right rod
Move the 1 disk to next circular right rod
Move the 3 disk to next circular right rod
Move the 1 disk to next circular right rod
Move the 2 disk to next circular right rod
Move the 1 disk to next circular right rod
Move the 4 disk to next circular right rod
Move the 1 disk to next circular right rod
Move the 2 disk to next circular right rod
Move the 1 disk to next circular right rod
Move the 3 disk to next circular right rod
Move the 1 disk to next circular right rod
Move the 2 disk to next circular right rod
Move the 1 disk to next circular right rod

Approach: The given problem can be solved based on the following observations:



  • It can be observed that to move the Nth disk, (N – 1)th disk needs to be moved. Therefore, to move (N – 1)th disk, (N – 2)th disk needs to be moved. This process goes on recursively.
  • The above procedure is similar to the setting the rightmost unset bit as it requires to set all the bits to right of it first.
  • Therefore, the idea is to print all the intermediate steps, every time setting the right most bit by incrementing the current number by 1.

Follow the steps below to solve the problem:

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to increment binary counter
int increment(int* counter, int n)
{
    int i = 0;
 
    while (true) {
 
        // Stores the Bitwise XOR of
        // the i-th bit of N and 1
        int a = counter[i] ^ 1;
 
        // Stores the Bitwise AND of
        // the i-th bit of N and 1
        int b = counter[i] & 1;
 
        // Swaps the i-th bit of N
        counter[i] = a;
 
        // If b is equal to zero
        if (b == 0)
            break;
 
        // Increment i by 1
        i = i + 1;
    }
 
    // Return i
    return i;
}
 
// Function to print order of movement
// of disks across three rods to place
// all disks on the third rod from the
// first rod
void TowerOfHanoi(int N)
{
    // Stores the binary reprsentation
    // of a state
    int counter[N] = { 0 };
 
    // Traverse the range [0, 2^N - 1]
    for (int step = 1;
         step <= pow(2, N) - 1; step++) {
 
        // Stores the position of the
        // rightmost unset bit
        int x = increment(counter, N) + 1;
 
        // Print the Xth bit
        cout << "Move disk " << x
             << " to next circular"
             << " right rod \n";
    }
}
 
// Driver Code
int main()
{
    int N = 3;
    TowerOfHanoi(N);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to increment binary counter
static int increment(int[] counter, int n)
{
    int i = 0;
 
    while (true)
    {
         
        // Stores the Bitwise XOR of
        // the i-th bit of N and 1
        int a = counter[i] ^ 1;
 
        // Stores the Bitwise AND of
        // the i-th bit of N and 1
        int b = counter[i] & 1;
 
        // Swaps the i-th bit of N
        counter[i] = a;
 
        // If b is equal to zero
        if (b == 0)
            break;
 
        // Increment i by 1
        i = i + 1;
    }
 
    // Return i
    return i;
}
 
// Function to print order of movement
// of disks across three rods to place
// all disks on the third rod from the
// first rod
static void TowerOfHanoi(int N)
{
     
    // Stores the binary reprsentation
    // of a state
    int[] counter=new int[N];
 
    // Traverse the range [0, 2^N - 1]
    for(int step = 1;
            step <= Math.pow(2, N) - 1;
            step++)
    {
 
        // Stores the position of the
        // rightmost unset bit
        int x = increment(counter, N) + 1;
 
        // Print the Xth bit
        System.out.println("Move disk " + x +
                           " to next circular" +
                           " right rod");
    }
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given inputs
    int N = 3;
     
    TowerOfHanoi(N);
}
}
 
// This code is contributed by offbeat

C#




// C# program for the above approach
using System;
class GFG
{
   
    // Function to increment binary counter
    static int increment(int[] counter, int n)
    {
        int i = 0;
        while (true)
        {
 
            // Stores the Bitwise XOR of
            // the i-th bit of N and 1
            int a = counter[i] ^ 1;
 
            // Stores the Bitwise AND of
            // the i-th bit of N and 1
            int b = counter[i] & 1;
 
            // Swaps the i-th bit of N
            counter[i] = a;
 
            // If b is equal to zero
            if (b == 0)
                break;
 
            // Increment i by 1
            i = i + 1;
        }
 
        // Return i
        return i;
    }
 
    // Function to print order of movement
    // of disks across three rods to place
    // all disks on the third rod from the
    // first rod
    static void TowerOfHanoi(int N)
    {
       
        // Stores the binary reprsentation
        // of a state
        int[] counter = new int[N];
 
        // Traverse the range [0, 2^N - 1]
        for (int step = 1;
             step <= (int)(Math.Pow(2, N) - 1); step++)
        {
 
            // Stores the position of the
            // rightmost unset bit
            int x = increment(counter, N) + 1;
 
            // Print the Xth bit
            Console.WriteLine("Move disk " + x
                              + " to next circular"
                              + " right rod ");
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int N = 3;
        TowerOfHanoi(N);
    }
}
 
// This code is contributed by ukasp.
Output: 
Move disk 1 to next circular right rod 
Move disk 2 to next circular right rod 
Move disk 1 to next circular right rod 
Move disk 3 to next circular right rod 
Move disk 1 to next circular right rod 
Move disk 2 to next circular right rod 
Move disk 1 to next circular right rod

 

Time Complexity: O(N * 2N)
Auxiliary Space: O(N)

Efficient Approach: The above approach can be optimized based on the observations that for M over the range [1, 2N – 1], source rod is equal to (m & (m – 1)) % 3 and the destination rod is equal to (m | (m – 1) + 1) % 3. Therefore, the idea is to iterate over the range [1, 2N – 1] and print the value of (i & (i – 1))%3 as source rod and (i | (i – 1) + 1)%3 as destination rod.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print order of movement
// of N disks across three rods to place
// all disks on the third rod from the
// first-rod using binary representation
void TowerOfHanoi(int N)
{
    // Iterate over the range [0, 2^N - 1]
    for (int x = 1;
         x <= pow(2, N) - 1; x++) {
 
        // Print the movement
        // of the current rod
        cout << "Move from Rod "
             << ((x & x - 1) % 3 + 1)
             << " to Rod "
             << (((x | x - 1) + 1) % 3 + 1)
             << endl;
    }
}
 
// Driver Code
int main()
{
    int N = 3;
    TowerOfHanoi(N);
    return 0;
}
Output: 
Move from Rod 1 to Rod 3
Move from Rod 1 to Rod 2
Move from Rod 3 to Rod 2
Move from Rod 1 to Rod 3
Move from Rod 2 to Rod 1
Move from Rod 2 to Rod 3
Move from Rod 1 to Rod 3

 

Time Complexity: O(2N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :