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

Program for Tower of Hanoi Algorithm

Last Updated : 17 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
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

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

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

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.
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
C
#include <stdio.h>

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);
    printf("Move disk %d from rod %c to rod %c\n", n, from_rod, to_rod);
    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;
}
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
// 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);
        console.log("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

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 



Master Data Structures and Algorithms at your own pace with our DSA Self-Paced course. In just 90 days, you’ll cover core concepts, solve real-world problems, and sharpen your problem-solving skills. Take the Three 90 Challenge: complete 90% of the course in 90 days and get a 90% refund. Stay motivated, track progress, and achieve DSA mastery. Start today!


Next Article

Similar Reads

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