Saturday, 16 September 2023

Tower of Hanoi



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: 

  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 can only be moved if it is the uppermost disk on a stack.
  3. No disk may be placed on top of a smaller disk.


Now, let’s try to imagine a scenario. Suppose we have a stack of three disks. Our job is to move this stack from source A to destination C. How do we do this?

Before we can get there, let’s imagine there is an intermediate point B.Three disks.

We can use B as a helper to finish this job. We are now ready to move on. Let’s go through each of the steps:
  1. Move the first disk from A to C
  2. Move the first disk from A to B
  3. Move the first disk from C to B
  4. Move the first disk from A to C
  5. Move the first disk from B to A
  6. Move the first disk from B to C
  7. Move the first disk from A to C


Boom! We have solved our problem.
Tower of Hanoi for 3 disks. Wikipedia

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.


Program in C
#include <stdio.h>

// C recursive function to solve tower of hanoi puzzle
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
    if (n == 1)
    {
        printf("\n Move disk 1 from rod %c to rod %c", from_rod,
to_rod);
        return;
    }
    towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
    printf("\n Move disk %d from rod %c to rod %c", n, from_rod,
to_rod);
    towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}

int main()
{
    int n = 4; // Number of disks
    towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
    return 0;
}
 

No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts