VOOZH about

URL: https://www.geeksforgeeks.org/dsa/c-program-for-tower-of-hanoi/

⇱ Tower of Hanoi Algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Tower of Hanoi Algorithm

Last Updated : 21 Jan, 2026

The Tower of Hanoi is a classic mathematical puzzle involving three rods (A, B, and C) and n disks of different sizes. Initially, all disks are stacked on rod A in decreasing order of diameter - the largest disk at the bottom and the smallest at the top.
Goal is to move the entire stack to another rod (rod C) while following these rules:

  • Move only one disk at a time.
  • At each step, you can take the top disk from any rod and place it on another rod.
  • A disk can only be moved if it is the topmost disk of a rod.
  • No larger disk may be placed on top of a smaller disk.

Examples:

Input: n = 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: n = 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

Illustrations:

[Approach] 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.

Follow the steps below to solve the problem:

  • Create a function towerOfHanoi where pass the n (current number of disk), fromRod, toRod, auxRod.
  • 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.

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

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

Comment