Open In App

Tower of Hanoi | Set 2

Last Updated : 28 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 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 representation
    // 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 representation
    // 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


Python3




# Python program for the above approach
import math
 
# Function to increment binary counter
def increment(counter, n):
    i = 0
     
    while (True):
         
        # Stores the Bitwise XOR of
        # the i-th bit of N and 1
        a = counter[i] ^ 1
         
        # Stores the Bitwise AND of
        # the i-th bit of N and 1
        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
 
# Function to print order of movement
# of disks across three rods to place
# all disks on the third rod from the
# first rod   
def TowerOfHanoi(N):
     
    # Stores the binary representation
    # of a state
    counter=[0 for i in range(N)]
     
    # Traverse the range [0, 2^N - 1]
    for step in range(1,int(math.pow(2,N))):
         
        # Stores the position of the
        # rightmost unset bit
        x = increment(counter, N) + 1
         
        #Print the Xth bit
        print("Move disk ",x," to next circular"," right rod")
 
# Driver code
N = 3
TowerOfHanoi(N)
         
# This code is contributed by rag2127


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 representation
        // 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.


Javascript




<script>
// Javascript implementation for the above approach
 
// Function to increment binary counter
function increment(counter, n)
{
    let i = 0;
 
    while (true)
    {
         
        // Stores the Bitwise XOR of
        // the i-th bit of N and 1
        let a = counter[i] ^ 1;
 
        // Stores the Bitwise AND of
        // the i-th bit of N and 1
        let 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
function TowerOfHanoi(N)
{
     
    // Stores the binary representation
    // of a state
    let counter= Array.from({length: N}, (_, i) => 0);
 
    // Traverse the range [0, 2^N - 1]
    for(let step = 1;
            step <= Math.pow(2, N) - 1;
            step++)
    {
 
        // Stores the position of the
        // rightmost unset bit
        let x = increment(counter, N) + 1;
 
        // Print the Xth bit
        document.write("Move disk " + x +
                           " to next circular" +
                           " right rod" + "<br/>");
    }
}
 
    // Driver Code
     
    // Given inputs
    let N = 3;
     
    TowerOfHanoi(N);
 
// This code is contributed by sanjoy_62.
</script>


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;
}


Java




// Java program for the above approach
class GFG{
     
// 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
static void TowerOfHanoi(int N)
{
     
    // Iterate over the range [0, 2^N - 1]
    for(int x = 1;
            x <= Math.pow(2, N) - 1; x++)
    {
         
        // Print the movement
        // of the current rod
        System.out.print("Move from Rod " +
                         ((x & x - 1) % 3 + 1) + " to Rod " +
                         (((x | x - 1) + 1) % 3 + 1) + "\n");
    }
}
 
// Driver Code
public static void main (String[] args)
{
    int N = 3;
     
    TowerOfHanoi(N);
}
}
 
// This code is contributed by jana_sayantan


Python3




# Python program for the above approach
import math
 
# 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
def TowerOfHanoi(N):
     
    # Iterate over the range [0, 2^N - 1]
    for x in range(1,int(math.pow(2, N)) ):
         
        # Print the movement
        # of the current rod
        print("Move from Rod " ,
                         ((x & x - 1) % 3 + 1) , " to Rod " ,
                         (((x | x - 1) + 1) % 3 + 1) )
 
# Driver Code
N=3
TowerOfHanoi(N)
 
# This code is contributed by avanitrachhadiya2155


C#




// C# program for the above approach
using System;
 
class GFG{
     
// 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
static void TowerOfHanoi(int N)
{
     
    // Iterate over the range [0, 2^N - 1]
    for(int x = 1;
            x <= Math.Pow(2, N) - 1; x++)
    {
         
        // Print the movement
        // of the current rod
        Console.Write("Move from Rod " +
                         ((x & x - 1) % 3 + 1) + " to Rod " +
                         (((x | x - 1) + 1) % 3 + 1) + "\n");
    }
}
 
// Driver Code
static void Main()
{
    int N = 3;
     
    TowerOfHanoi(N);
}
}
 
// This code is contributed by SoumikMondal


Javascript




<script>
 
// Javascript program for the above approach
 
// 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
function TowerOfHanoi(N)
{
    // Iterate over the range [0, 2^N - 1]
    for (let x = 1;
         x <= Math.pow(2, N) - 1; x++) {
 
        // Print the movement
        // of the current rod
        document.write("Move from Rod "
             + ((x & x - 1) % 3 + 1)
             + " to Rod "
             + (((x | x - 1) + 1) % 3 + 1)
             + "<br>");
    }
}
 
// Driver Code
    let N = 3;
    TowerOfHanoi(N);
 
</script>


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)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads