The Wayback Machine - https://web.archive.org/web/20241129030520/https://www.geeksforgeeks.org/c-program-for-tower-of-hanoi/
Open In App

Program for Tower of Hanoi Algorithm

Last Updated : 09 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Tower of Hanoi is a mathematical puzzle where we have three rods (A, B, and C) and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest disk is placed on the top and they are on rod A. The objective of the puzzle is to move the entire stack to another rod (here considered C), obeying the following simple rules: 

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  • No disk may be placed on top of a smaller disk.

Examples:

Input: 2
Output: Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C

Input: 3
Output: Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C

The following video shows the solution of Tower of Hanoi for input (N) = 3 –


Recommended Practice

Tower of Hanoi using Recursion:

 The idea is to use the helper node to reach the destination using recursion. Below is the pattern for this problem:

  • Shift ‘N-1’ disks from ‘A’ to ‘B’, using C.
  • Shift last disk from ‘A’ to ‘C’.
  • Shift ‘N-1’ disks from ‘B’ to ‘C’, using A.
faq.disk3

Image illustration for 3 disks

Follow the steps below to solve the problem:

  • Create a function towerOfHanoi where pass the N (current number of disk), from_rod, to_rod, aux_rod.
  • Make a function call for N – 1 th disk.
  • Then print the current the disk along with from_rod and to_rod
  • Again make a function call for N – 1 th disk.

Below is the implementation of the above approach.

C++
// C++ recursive function to
// solve tower of hanoi puzzle
#include <bits/stdc++.h>
using namespace std;

void towerOfHanoi(int n, char from_rod, char to_rod,
                  char aux_rod)
{
    if (n == 0) {
        return;
    }
    towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
    cout << "Move disk " << n << " from rod " << from_rod
         << " to rod " << to_rod << endl;
    towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}

// Driver code
int main()
{
    int N = 3;

    // A, B and C are names of rods
    towerOfHanoi(N, 'A', 'C', 'B');
    return 0;
}

// This is code is contributed by rathbhupendra
Java
// JAVA recursive function to
// solve tower of hanoi puzzle
import java.io.*;
import java.math.*;
import java.util.*;
class GFG {
    static void towerOfHanoi(int n, char from_rod,
                             char to_rod, char aux_rod)
    {
        if (n == 0) {
            return;
        }
        towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
        System.out.println("Move disk " + n + " from rod "
                           + from_rod + " to rod "
                           + to_rod);
        towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
    }

    // Driver code
    public static void main(String args[])
    {
        int N = 3;

        // A, B and C are names of rods
        towerOfHanoi(N, 'A', 'C', 'B');
    }
}

// This code is contributed by jyoti369
Python
# Recursive Python function to solve tower of hanoi


def TowerOfHanoi(n, from_rod, to_rod, aux_rod):
    if n == 0:
        return
    TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
    print("Move disk", n, "from rod", from_rod, "to rod", to_rod)
    TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)


# Driver code
N = 3

# A, C, B are the name of rods
TowerOfHanoi(N, 'A', 'C', 'B')

# Contributed By Harshit Agrawal
C#
// C# recursive program to solve tower of hanoi puzzle
using System;
class GFG {
    static void towerOfHanoi(int n, char from_rod,
                             char to_rod, char aux_rod)
    {
        if (n == 0) {
            return;
        }
        towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
        Console.WriteLine("Move disk " + n + " from rod "
                          + from_rod + " to rod " + to_rod);
        towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
    }

    //  Driver method
    public static void Main(String[] args)
    {
        int N = 3;

        // A, B and C are names of rods
        towerOfHanoi(N, 'A', 'C', 'B');
    }
}

// This code is contributed by shivanisinghss2110
JavaScript
<script>
// javascript recursive function to 
// solve tower of hanoi puzzle 
function towerOfHanoi(n, from_rod,  to_rod,  aux_rod)
{
        if (n == 0)
        {
            return;
        }
        towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
        document.write("Move disk " + n + " from rod " + from_rod +
        " to rod " + to_rod+"<br/>");
        towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
    }

    // Driver code
    var N = 3;
    
    // A, B and C are names of rods
    towerOfHanoi(N, 'A', 'C', 'B');

// This code is contributed by gauravrajput1
</script>
PHP
<?php

// Tower of Hanoi (n-disk) algorithm in PHP with Display of Pole/rod 
// Contents the 3 poles representation
$poles = array(array(), array(), array());

function TOH($n, $A="A", $B="B", $C="C"){
    
    if ($n > 0){
        TOH($n-1, $A, $C, $B);
        echo "Move disk from rod $A to rod $C \n";
        move($A, $C);
        dispPoles();
        TOH($n-1, $B, $A, $C);
    }
    else {
        return;
    }
}

function initPoles($n){
    global $poles;

    for ($i=$n; $i>=1; --$i){
        $poles[0][] = $i;
    }
}


function move($source, $destination){
    global $poles;
    
    // get source and destination pointers
    if ($source=="A") $ptr1=0;
    elseif ($source=="B") $ptr1 = 1;
    else $ptr1 = 2;
    
    if ($destination=="A") $ptr2 = 0;
    elseif ($destination=="B") $ptr2 = 1;
    else $ptr2 = 2;
    
    $top = array_pop($poles[$ptr1]);
    array_push($poles[$ptr2], $top);
}

function dispPoles(){  
    global $poles;
    echo "A: [".implode(", ", $poles[0])."] ";
    echo "B: [".implode(", ", $poles[1])."] ";
    echo "C: [".implode(", ", $poles[2])."] ";
    echo "\n\n";
}

$N = 3;
initPoles($N);
echo "Tower of Hanoi Solution for $numdisks disks: \n\n";
dispPoles();
TOH($N);

// This code is contributed by ShreyakChakraborty
?>

Output
Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C

Time complexity: O(2N), There are two possibilities for every disk. Therefore, 2 * 2 * 2 * . . . * 2(N times) is 2N
Auxiliary Space: O(N), Function call stack space

Related Articles 



Previous Article
Next Article

Similar Reads

Time Complexity Analysis | Tower Of Hanoi (Recursion)
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk ca
2 min read
Cost Based Tower of Hanoi
The standard Tower of Hanoi problem is explained here . In the standard problem, all the disc transactions are considered identical. Given a 3x3 matrix costs[][] containing the costs of transfer of disc between the rods where costs[i][j] stores the cost of transferring a disc from rod i to rod j. Cost of transfer between the same rod is 0. Hence th
10 min read
Twisted Tower of Hanoi Problem
The basic version of the Tower of Hanoi can be found here. It is a twisted Tower of Hanoi problem. In which, all rules are the same with an addition of a rule: You can not move any disk directly from the first rod to last rod i.e., If you want to move a disk from the first rod to the last rod then you have to move the first rod to the middle rod fi
7 min read
Tower of Hanoi | Set 2
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 = 3Output:Move the 1 disk to next circular right rodMove the 2 disk to next circular right rodMove the 1 disk to next circular right rodMove the 3 disk to next circular ri
12 min read
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 pol
15+ min read
Recursive Tower of Hanoi using 4 pegs / rods
Tower of Hanoi is a mathematical puzzle. Traditionally, It consists of three poles and a number of disks of different sizes which can slide onto any poles. 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
8 min read
Maximize height of tower using elements from one of the given Subarrays
Given an array arr[] of length N, two arrays start[] and end[] of size M each where {start[i], end[i]} denotes a subarray of arr[] and an integer base, the task is to determine the maximum height of a tower with given base that can be formed using elements from a single subarray bounded by any {start[i], end[i]} and satisfying the following conditi
10 min read
Minimum number of towers required such that every house is in the range of at least one tower
Given a map of the city and the network range, the task is to determine the minimum number of the tower so that every house is within range of at least one tower. Each tower must be installed on top of an existing house. Examples: Input: range : 1 house : 1 2 3 4 5 Output: 2 Input: range : 2 house : 7 2 4 6 5 9 12 11 Output: 3 All cities can be cov
7 min read
Check if the tower of sight issue occurs or not
Given four co-ordinates A, B, C and D where towers need to be constructed, the task is to check if the tower of sight issue occurs or not. Tower of sight issue occurs if the towers at A or C lies in the line joining B and D or vice versa. Examples: Input: A = (0, 0), B = (0, -2), C = (2, 0), D = (0, 2) Output: Yes Explanation: Tower A lies in the l
10 min read
Finding nearest shortest tower in Array
Given an array arr[] where each element (arr[i]) represents the height of the tower. Find the nearest possible tower that is shorter than it for each tower. You can look left or right on both sides. If two smaller towers are at the same distance, pick the smallest tower.If two towers have the same height, we choose the one with a smaller index.Exam
8 min read
Minimize cost of operation to equalize tower heights
Given heights of n (n <=10000) towers as an array h[]; we need to bring every tower to same height by either adding or removing blocks in a tower. Every addition or removal operation costs a different value in a different tower. The objective is to minimize this cost. Examples: Input : Tower heights h[] = {1, 2, 3} Costs of operations cost[] = {
11 min read
Furthest Reachable Tower using Blocks and Ladders
Given an array heights[] of size N, where heights[i] is the height of the ith tower. We are standing at the 0th tower with B blocks and L ladders and we have to reach the furthest tower possible by jumping on adjacent towers. For ith tower, If heights[i + 1] <= heights[i], then we can simply jump to the next tower. Else,If heights[i + 1] > he
13 min read
Edge Relaxation Property for Dijkstra’s Algorithm and Bellman Ford's Algorithm
In the field of graph theory, various shortest path algorithms especially Dijkstra’s algorithm and Bellmann-Ford’s algorithm repeatedly employ the use of the technique called Edge Relaxation. The idea of relaxation is the same in both algorithms and it is by understanding, the 'Relaxation property' we can fully grasp the working of the two algorith
4 min read
Difference between Greedy Algorithm and Divide and Conquer Algorithm
Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of making the locally optimal choice at each stage wit
3 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
What is the stupidest sorting algorithm? (Worst Sorting Algorithm)
Bogo sort stands out as the undisputed champion of stupidity. Unlike other sorting algorithms that follow a structured approach, Bogo sort relies on sheer luck and randomness to achieve its goal. How Bogo Sort Works?Bogo sort operates on the following principle: Randomly shuffle the elements in the list.Check if the list is sorted.If the list is no
2 min read
Difference Between Dijkstra's Algorithm and A* Search Algorithm
Dijkstra's Algorithm and A* Algorithm are two of the most widely used techniques. Both are employed to the find the shortest path between the nodes in a graph but they have distinct differences in their approaches and applications. Understanding these differences is crucial for the selecting the appropriate algorithm for the given problem. What is
3 min read
Z algorithm (Linear time pattern searching Algorithm)
This algorithm efficiently locates all instances of a specific pattern within a text in linear time. If the length of the text is "n" and the length of the pattern is "m," then the total time taken is O(m + n), with a linear auxiliary space. It is worth noting that the time and auxiliary space of this algorithm is the same as the KMP algorithm, but
13 min read
Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
Given two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120. For simplicity, let the length of two strings be same and be n. A Naive Approach is to follow the process we study in school. One by one take all bits o
15+ min read
Difference between Algorithm, Pseudocode and Program
In this post, we will discuss the most common misconception that an algorithm and a pseudocode is one of the same things. No, they are not! Let us take a look at definitions first, Algorithm : Systematic logical approach which is a well-defined, step-by-step procedure that allows a computer to solve a problem. Pseudocode : It is a simpler version o
5 min read
Program for Best Fit algorithm in Memory Management using Linked List
Best fit algorithm for memory management: The memory partition in which there is a minimum loss on the allocation of the process is the best-fit memory partition that is allocated to the process.We have already discussed one best-fit algorithm using arrays in this article. However, here we are going to look into another approach using a linked list
15+ min read
Java Program to Implement Commentz-Walter Algorithm
The Commentz-Walter algorithm is a string-matching algorithm that is used to search for a given pattern in a text string. It is a variant of the Knuth-Morris-Pratt (KMP) algorithm, which is a well-known algorithm for string matching. This algorithm works by preprocessing the pattern string to create a failure function that encodes the information a
6 min read
Javascript Program for Block swap algorithm for array rotation
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make array Algorithm : Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change ABl
3 min read
Javascript Program for Reversal algorithm for array rotation
Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. Example : Input : arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output : arr[] = [3, 4, 5, 6, 7, 1, 2] Rotation of the above array by 2 will make array Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. The first 3 methods to rotate an array by
3 min read
Java Program for Dijkstra's Algorithm with Path Printing
import java.util.Scanner; //Scanner Function to take in the Input Values public class Dijkstra { static Scanner scan; // scan is a Scanner Object public static void main(String[] args) { int[] preD = new int[5]; int min = 999, nextNode = 0; // min holds the minimum value, nextNode holds the value for the next node. scan = new Scanner(System.in); in
2 min read
Program for First Fit algorithm in Memory Management
Prerequisite : Partition Allocation MethodsIn the first fit, the partition is allocated which is first sufficient from the top of Main Memory.Example : Input : blockSize[] = {100, 500, 200, 300, 600}; processSize[] = {212, 417, 112, 426}; Output: Process No. Process Size Block no. 1 212 2 2 417 5 3 112 2 4 426 Not AllocatedIts advantage is that it
8 min read
Program for Best Fit algorithm in Memory Management
Prerequisite : Partition allocation methodsBest fit allocates the process to a partition which is the smallest sufficient partition among the free available partitions. Example: Input : blockSize[] = {100, 500, 200, 300, 600}; processSize[] = {212, 417, 112, 426}; Output: Process No. Process Size Block no. 1 212 4 2 417 2 3 112 3 4 426 5 Implementa
8 min read
Program for Worst Fit algorithm in Memory Management
Prerequisite : Partition allocation methodsWorst Fit allocates a process to the partition which is largest sufficient among the freely available partitions available in the main memory. If a large process comes at a later stage, then memory will not have space to accommodate it. Example: Input : blockSize[] = {100, 500, 200, 300, 600}; processSize[
8 min read
Program for Least Recently Used (LRU) Page Replacement algorithm
Prerequisite: Page Replacement AlgorithmsIn operating systems that use paging for memory management, page replacement algorithm are needed to decide which page needed to be replaced when new page comes in. Whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly
14 min read
Discrete Cosine Transform (Algorithm and Program)
Image Compression : Image is stored or transmitted with having pixel value. It can be compressed by reducing the value its every pixel contains. Image compression is basically of two types : Lossless compression : In this type of compression, after recovering image is exactly become same as that was before applying compression techniques and so, it
11 min read
three90RightbarBannerImg