Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Program for Tower of Hanoi Algorithm
Next article icon

Program for Tower of Hanoi Algorithm

Last Updated : 17 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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 

  • Recursive Functions
  • Iterative solution to TOH puzzle
  • Quiz on Recursion



Next Article
Program for Tower of Hanoi Algorithm

K

kartik
Improve
Article Tags :
  • Stack
  • Divide and Conquer
  • Recursion
  • DSA
  • Basic Coding Problems
Practice Tags :
  • Divide and Conquer
  • Recursion
  • Stack

Similar Reads

    Introduction to Recursion
    The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
    14 min read
    What is Recursion?
    Recursion is defined as a process which calls itself directly or indirectly and the corresponding function is called a recursive function.Example 1 : Sum of Natural Numbers Let us consider a problem to find the sum of natural numbers, there are several ways of doing that but the simplest approach is
    8 min read
    Difference between Recursion and Iteration
    A program is called recursive when an entity calls itself. A program is called iterative when there is a loop (or repetition).Example: Program to find the factorial of a number C++ // C++ program to find factorial of given number #include<bits/stdc++.h> using namespace std; // ----- Recursion
    6 min read
    Types of Recursions
    What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inord
    15+ min read
    Finite and Infinite Recursion with examples
    The process in which a function calls itself directly or indirectly is called Recursion and the corresponding function is called a Recursive function. Using Recursion, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Tr
    6 min read
    What is Tail Recursion
    Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call.For example the following function print() is tail recursive.C++// An example of tail recursive funct
    7 min read
    What is Implicit recursion?
    What is Recursion? Recursion is a programming approach where a function repeats an action by calling itself, either directly or indirectly. This enables the function to continue performing the action until a particular condition is satisfied, such as when a particular value is reached or another con
    5 min read
    Why is Tail Recursion optimization faster than normal Recursion?
    What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recur
    4 min read
    Recursive Functions
    A Recursive function can be defined as a routine that calls itself directly or indirectly. In other words, a recursive function is a function that solves a problem by solving smaller instances of the same problem. This technique is commonly used in programming to solve problems that can be broken do
    4 min read
    Difference Between Recursion and Induction
    Recursion and induction are fundamental ideas in computer science and mathematics that might be regularly used to solve problems regarding repetitive structures. Recursion is a programming technique in which a function calls itself to solve the problem, whilst induction is a mathematical proof techn
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences