Data Structure & Algorithms - Tower of Hanoi


Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more than one rings is as depicted −

Tower Of Hanoi

These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one sits over the larger one. There are other variations of the puzzle where the number of disks increase, but the tower count remains the same.

Rules

The mission is to move all the disks to some another tower without violating the sequence of arrangement. A few rules to be followed for Tower of Hanoi are −

  • Only one disk can be moved among the towers at any given time.
  • Only the "top" disk can be removed.
  • No large disk can sit over a small disk.

Following is an animated representation of solving a Tower of Hanoi puzzle with three disks.

Tower Of Hanoi

Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps.

Algorithm

To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with lesser amount of disks, say → 1 or 2. We mark three towers with name, source, destination and aux (only to help moving the disks). If we have only one disk, then it can easily be moved from source to destination peg.

If we have 2 disks −

  • First, we move the smaller (top) disk to aux peg.
  • Then, we move the larger (bottom) disk to destination peg.
  • And finally, we move the smaller disk from aux to destination peg.
Tower Of Hanoi with Two Disks

So now, we are in a position to design an algorithm for Tower of Hanoi with more than two disks. We divide the stack of disks in two parts. The largest disk (nth disk) is in one part and all other (n-1) disks are in the second part.

Our ultimate aim is to move disk n from source to destination and then put all other (n1) disks onto it. We can imagine to apply the same in a recursive way for all given set of disks.

The steps to follow are −

Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest

A recursive algorithm for Tower of Hanoi can be driven as follows −

START
Procedure Hanoi(disk, source, dest, aux)

   IF disk == 1, THEN
      move disk from source to dest             
   ELSE
      Hanoi(disk - 1, source, aux, dest)     // Step 1
      move disk from source to dest          // Step 2
      Hanoi(disk - 1, aux, dest, source)     // Step 3
   END IF
   
END Procedure
STOP

Example

#include <stdio.h>
#include <stdbool.h>
#define MAX 10
int list[MAX] = {1,8,4,6,0,3,5,2,7,9};
void display(){
   int i;
   printf("[");
   // navigate through all items 
   for(i = 0; i < MAX; i++) {
      printf("%d ",list[i]);
   }
   printf("]\n");
}
void bubbleSort() {
   int temp;
   int i,j;
   bool swapped = false;       
   // loop through all numbers 
   for(i = 0; i < MAX-1; i++) { 
      swapped = false;	
      // loop through numbers falling ahead 
      for(j = 0; j < MAX-1-i; j++) {
         printf("Items compared: [ %d, %d ] ", list[j],list[j+1]);
         // check if next number is lesser than current no
         //   swap the numbers. 
         //  (Bubble up the highest number) 		
         if(list[j] > list[j+1]) {
            temp = list[j];
            list[j] = list[j+1];
            list[j+1] = temp;
            swapped = true;
            printf(" => swapped [%d, %d]\n",list[j],list[j+1]);
         } else {
            printf(" => not swapped\n");
         }
      }
      // if no number was swapped that means 
      //   array is sorted now, break the loop. 
      if(!swapped) {
         break;
      }
      printf("Iteration %d#: ",(i+1)); 
      display();                     
   }    
}
int main() {
   printf("Input Array: ");
   display();
   printf("\n");
   bubbleSort();
   printf("\nOutput Array: ");
   display();
}

Output

Input Array: [1 8 4 6 0 3 5 2 7 9 ]

Items compared: [ 1, 8 ]  => not swapped
Items compared: [ 8, 4 ]  => swapped [4, 8]
Items compared: [ 8, 6 ]  => swapped [6, 8]
Items compared: [ 8, 0 ]  => swapped [0, 8]
Items compared: [ 8, 3 ]  => swapped [3, 8]
Items compared: [ 8, 5 ]  => swapped [5, 8]
Items compared: [ 8, 2 ]  => swapped [2, 8]
Items compared: [ 8, 7 ]  => swapped [7, 8]
Items compared: [ 8, 9 ]  => not swapped
Iteration 1#: [1 4 6 0 3 5 2 7 8 9 ]
Items compared: [ 1, 4 ]  => not swapped
Items compared: [ 4, 6 ]  => not swapped
Items compared: [ 6, 0 ]  => swapped [0, 6]
Items compared: [ 6, 3 ]  => swapped [3, 6]
Items compared: [ 6, 5 ]  => swapped [5, 6]
Items compared: [ 6, 2 ]  => swapped [2, 6]
Items compared: [ 6, 7 ]  => not swapped
Items compared: [ 7, 8 ]  => not swapped
Iteration 2#: [1 4 0 3 5 2 6 7 8 9 ]
Items compared: [ 1, 4 ]  => not swapped
Items compared: [ 4, 0 ]  => swapped [0, 4]
Items compared: [ 4, 3 ]  => swapped [3, 4]
Items compared: [ 4, 5 ]  => not swapped
Items compared: [ 5, 2 ]  => swapped [2, 5]
Items compared: [ 5, 6 ]  => not swapped
Items compared: [ 6, 7 ]  => not swapped
Iteration 3#: [1 0 3 4 2 5 6 7 8 9 ]
Items compared: [ 1, 0 ]  => swapped [0, 1]
Items compared: [ 1, 3 ]  => not swapped
Items compared: [ 3, 4 ]  => not swapped
Items compared: [ 4, 2 ]  => swapped [2, 4]
Items compared: [ 4, 5 ]  => not swapped
Items compared: [ 5, 6 ]  => not swapped
Iteration 4#: [0 1 3 2 4 5 6 7 8 9 ]
Items compared: [ 0, 1 ]  => not swapped
Items compared: [ 1, 3 ]  => not swapped
Items compared: [ 3, 2 ]  => swapped [2, 3]
Items compared: [ 3, 4 ]  => not swapped
Items compared: [ 4, 5 ]  => not swapped
Iteration 5#: [0 1 2 3 4 5 6 7 8 9 ]
Items compared: [ 0, 1 ]  => not swapped
Items compared: [ 1, 2 ]  => not swapped
Items compared: [ 2, 3 ]  => not swapped
Items compared: [ 3, 4 ]  => not swapped

Output Array: [0 1 2 3 4 5 6 7 8 9 ]
// C++ Code for Tower of Hanoi
#include <iostream>
#include <array>
#include <algorithm>
const int MAX = 10;
std::array<int, MAX> list = {1, 8, 4, 6, 0, 3, 5, 2, 7, 9};
void display() {
   std::cout << "[";
   // navigate through all items 
   for (int i = 0; i < MAX; i++) {
      std::cout << list[i] << " ";
   }	
   std::cout << "]\n";
}
void bubbleSort() {
   int temp;
   bool swapped = false;       
   // loop through all numbers 
   for (int i = 0; i < MAX - 1; i++) { 
      swapped = false;		
      // loop through numbers falling ahead 
      for (int j = 0; j < MAX - 1 - i; j++) {
         std::cout << "Items compared: [" << list[j] << ", " << list[j+1] << "] ";
         // check if next number is lesser than current no
         // swap the numbers. 
         // (Bubble up the highest number) 		
         if (list[j] > list[j+1]) {
            std::swap(list[j], list[j+1]);
            swapped = true;
            std::cout << "=> swapped [" << list[j] << ", " << list[j+1] << "]\n";
         } else {
            std::cout << "=> not swapped\n";
         }
      }
      // if no number was swapped that means 
      // array is sorted now, break the loop. 
      if (!swapped) {
         break;
      }  
      std::cout << "Iteration " << (i+1) << "#: "; 
      display();                     
   }    
}
int main() {
   std::cout << "Input Array: ";
   display();
   std::cout << "\n";
   bubbleSort();
   std::cout << "\nOutput Array: ";
   display();
   return 0;
}

Output

Input Array: [1 8 4 6 0 3 5 2 7 9 ]

Items compared: [1, 8] => not swapped
Items compared: [8, 4] => swapped [4, 8]
Items compared: [8, 6] => swapped [6, 8]
Items compared: [8, 0] => swapped [0, 8]
Items compared: [8, 3] => swapped [3, 8]
Items compared: [8, 5] => swapped [5, 8]
Items compared: [8, 2] => swapped [2, 8]
Items compared: [8, 7] => swapped [7, 8]
Items compared: [8, 9] => not swapped
Iteration 1#: [1 4 6 0 3 5 2 7 8 9 ]
Items compared: [1, 4] => not swapped
Items compared: [4, 6] => not swapped
Items compared: [6, 0] => swapped [0, 6]
Items compared: [6, 3] => swapped [3, 6]
Items compared: [6, 5] => swapped [5, 6]
Items compared: [6, 2] => swapped [2, 6]
Items compared: [6, 7] => not swapped
Items compared: [7, 8] => not swapped
Iteration 2#: [1 4 0 3 5 2 6 7 8 9 ]
Items compared: [1, 4] => not swapped
Items compared: [4, 0] => swapped [0, 4]
Items compared: [4, 3] => swapped [3, 4]
Items compared: [4, 5] => not swapped
Items compared: [5, 2] => swapped [2, 5]
Items compared: [5, 6] => not swapped
Items compared: [6, 7] => not swapped
Iteration 3#: [1 0 3 4 2 5 6 7 8 9 ]
Items compared: [1, 0] => swapped [0, 1]
Items compared: [1, 3] => not swapped
Items compared: [3, 4] => not swapped
Items compared: [4, 2] => swapped [2, 4]
Items compared: [4, 5] => not swapped
Items compared: [5, 6] => not swapped
Iteration 4#: [0 1 3 2 4 5 6 7 8 9 ]
Items compared: [0, 1] => not swapped
Items compared: [1, 3] => not swapped
Items compared: [3, 2] => swapped [2, 3]
Items compared: [3, 4] => not swapped
Items compared: [4, 5] => not swapped
Iteration 5#: [0 1 2 3 4 5 6 7 8 9 ]
Items compared: [0, 1] => not swapped
Items compared: [1, 2] => not swapped
Items compared: [2, 3] => not swapped
Items compared: [3, 4] => not swapped

Output Array: [0 1 2 3 4 5 6 7 8 9 ]
//Java Code for Tower of Hanoi
import java.util.Arrays;
public class BubbleSort {
    public static final int MAX = 10;
    public static int[] list = {1, 8, 4, 6, 0, 3, 5, 2, 7, 9};
    public static void display() {
        System.out.print("[");
        // navigate through all items
        for (int i = 0; i < MAX; i++) {
            System.out.print(list[i] + " ");
        }
        System.out.println("]");
    }
    public static void bubbleSort() {
        boolean swapped;
        // loop through all numbers
        for (int i = 0; i < MAX - 1; i++) {
            swapped = false;
            // loop through numbers falling ahead
            for (int j = 0; j < MAX - 1 - i; j++) {
                System.out.print("Items compared: [" + list[j] + ", " + list[j + 1] + "] ");
                // check if next number is lesser than current no
                // swap the numbers.
                // (Bubble up the highest number)
                if (list[j] > list[j + 1]) {
                    int temp = list[j];
                    list[j] = list[j + 1];
                    list[j + 1] = temp;
                    swapped = true;
                    System.out.println("=> swapped [" + list[j] + ", " + list[j + 1] + "]");
                } else {
                    System.out.println("=> not swapped");
                }
            }
            // if no number was swapped that means
            // array is sorted now, break the loop.
            if (!swapped) {
                break;
            }
            System.out.print("Iteration " + (i + 1) + "#: ");
            display();
        }
    }
    public static void main(String[] args) {
        System.out.print("Input Array: ");
        display();
        System.out.println();
        bubbleSort();
        System.out.print("\nOutput Array: ");
        display();
    }
}

Output

Input Array: [1 8 4 6 0 3 5 2 7 9 ]
Items compared: [1, 8] => not swapped
Items compared: [8, 4] => swapped [4, 8]
Items compared: [8, 6] => swapped [6, 8]
Items compared: [8, 0] => swapped [0, 8]
Items compared: [8, 3] => swapped [3, 8]
Items compared: [8, 5] => swapped [5, 8]
Items compared: [8, 2] => swapped [2, 8]
Items compared: [8, 7] => swapped [7, 8]
Items compared: [8, 9] => not swapped
Iteration 1#: [1 4 6 0 3 5 2 7 8 9 ]
Items compared: [1, 4] => not swapped
Items compared: [4, 6] => not swapped
Items compared: [6, 0] => swapped [0, 6]
Items compared: [6, 3] => swapped [3, 6]
Items compared: [6, 5] => swapped [5, 6]
Items compared: [6, 2] => swapped [2, 6]
Items compared: [6, 7] => not swapped
Items compared: [7, 8] => not swapped
Iteration 2#: [1 4 0 3 5 2 6 7 8 9 ]
Items compared: [1, 4] => not swapped
Items compared: [4, 0] => swapped [0, 4]
Items compared: [4, 3] => swapped [3, 4]
Items compared: [4, 5] => not swapped
Items compared: [5, 2] => swapped [2, 5]
Items compared: [5, 6] => not swapped
Items compared: [6, 7] => not swapped
Iteration 3#: [1 0 3 4 2 5 6 7 8 9 ]
Items compared: [1, 0] => swapped [0, 1]
Items compared: [1, 3] => not swapped
Items compared: [3, 4] => not swapped
Items compared: [4, 2] => swapped [2, 4]
Items compared: [4, 5] => not swapped
Items compared: [5, 6] => not swapped
Iteration 4#: [0 1 3 2 4 5 6 7 8 9 ]
Items compared: [0, 1] => not swapped
Items compared: [1, 3] => not swapped
Items compared: [3, 2] => swapped [2, 3]
Items compared: [3, 4] => not swapped
Items compared: [4, 5] => not swapped
Iteration 5#: [0 1 2 3 4 5 6 7 8 9 ]
Items compared: [0, 1] => not swapped
Items compared: [1, 2] => not swapped
Items compared: [2, 3] => not swapped
Items compared: [3, 4] => not swapped
Output Array: [0 1 2 3 4 5 6 7 8 9 ]
#Python Code for Tower of Hanoi
MAX = 10
list = [1, 8, 4, 6, 0, 3, 5, 2, 7, 9]
def display():
    print("[", end="")
    # navigate through all items
    for i in range(MAX):
        print(list[i], end=" ")
    print("]")
def bubbleSort():
    swapped = False
    # loop through all numbers
    for i in range(MAX - 1):
        swapped = False
        # loop through numbers falling ahead
        for j in range(MAX - 1 - i):
            print("Items compared: [",
                  list[j],
                  ", ",
                  list[j + 1],
                  "] ",
                  end="")
            # check if next number is lesser than the current number
            # swap the numbers.
            # (Bubble up the highest number)
            if list[j] > list[j + 1]:
                temp = list[j]
                list[j] = list[j + 1]
                list[j + 1] = temp
                swapped = True
                print("=> swapped [", list[j], ", ", list[j + 1], "]")
            else:
                print("=> not swapped")
        # if no number was swapped, the array is sorted now, break the loop
        if not swapped:
            break
        print("Iteration", (i + 1), "#: ", end="")
        display()
print("Input Array: ", end="")
display()
print()
bubbleSort()
print("\nOutput Array: ", end="")
display()

Output

Input Array: [1 8 4 6 0 3 5 2 7 9 ]
Items compared: [ 1 ,  8 ] => not swapped
Items compared: [ 8 ,  4 ] => swapped [ 4 ,  8 ]
Items compared: [ 8 ,  6 ] => swapped [ 6 ,  8 ]
Items compared: [ 8 ,  0 ] => swapped [ 0 ,  8 ]
Items compared: [ 8 ,  3 ] => swapped [ 3 ,  8 ]
Items compared: [ 8 ,  5 ] => swapped [ 5 ,  8 ]
Items compared: [ 8 ,  2 ] => swapped [ 2 ,  8 ]
Items compared: [ 8 ,  7 ] => swapped [ 7 ,  8 ]
Items compared: [ 8 ,  9 ] => not swapped
Iteration 1 #: [1 4 6 0 3 5 2 7 8 9 ]
Items compared: [ 1 ,  4 ] => not swapped
Items compared: [ 4 ,  6 ] => not swapped
Items compared: [ 6 ,  0 ] => swapped [ 0 ,  6 ]
Items compared: [ 6 ,  3 ] => swapped [ 3 ,  6 ]
Items compared: [ 6 ,  5 ] => swapped [ 5 ,  6 ]
Items compared: [ 6 ,  2 ] => swapped [ 2 ,  6 ]
Items compared: [ 6 ,  7 ] => not swapped
Items compared: [ 7 ,  8 ] => not swapped
Iteration 2 #: [1 4 0 3 5 2 6 7 8 9 ]
Items compared: [ 1 ,  4 ] => not swapped
Items compared: [ 4 ,  0 ] => swapped [ 0 ,  4 ]
Items compared: [ 4 ,  3 ] => swapped [ 3 ,  4 ]
Items compared: [ 4 ,  5 ] => not swapped
Items compared: [ 5 ,  2 ] => swapped [ 2 ,  5 ]
Items compared: [ 5 ,  6 ] => not swapped
Items compared: [ 6 ,  7 ] => not swapped
Iteration 3 #: [1 0 3 4 2 5 6 7 8 9 ]
Items compared: [ 1 ,  0 ] => swapped [ 0 ,  1 ]
Items compared: [ 1 ,  3 ] => not swapped
Items compared: [ 3 ,  4 ] => not swapped
Items compared: [ 4 ,  2 ] => swapped [ 2 ,  4 ]
Items compared: [ 4 ,  5 ] => not swapped
Items compared: [ 5 ,  6 ] => not swapped
Iteration 4 #: [0 1 3 2 4 5 6 7 8 9 ]
Items compared: [ 0 ,  1 ] => not swapped
Items compared: [ 1 ,  3 ] => not swapped
Items compared: [ 3 ,  2 ] => swapped [ 2 ,  3 ]
Items compared: [ 3 ,  4 ] => not swapped
Items compared: [ 4 ,  5 ] => not swapped
Iteration 5 #: [0 1 2 3 4 5 6 7 8 9 ]
Items compared: [ 0 ,  1 ] => not swapped
Items compared: [ 1 ,  2 ] => not swapped
Items compared: [ 2 ,  3 ] => not swapped
Items compared: [ 3 ,  4 ] => not swapped

Output Array: [0 1 2 3 4 5 6 7 8 9 ]
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements