Rotate image (square matrix) by 90 deg
Tue, 06 May 2025
Tower of Hanoi is a Mathematical Game. There are 3 pegs (Rods) and number of discs, each of different size, which can be inserted into the rods. All discs are initially inserted into one rod in increasing order (smallest at the top and largest disc at the bottom). You have to move all the discs from source rod to Destination rod, with below 2 restrictions:


/* The three char represents the characters representing three rods * and n is the number of discs (initially in s) */ void towerOfHanoi(char s, char d, char e, int n)
Solution:
The solution to this problem can be easily thought in a recursive approach. The Problem:
Move n Discs from S to D using E
Can be solved in 3 steps:
Step-1: Move n-1 discs from S to E using D Step-2: Move the nth disc from S to E Step-3: Move n-1 discs from E to D using S
If you notice, the Step-1 & Step-3 are recursive calls to the same function. Hence the code of the function will be:
void towerOfHanoi(char s, char d, char e, unsigned int n)
{
if(n > 0)
{
towerOfHanoi(s, e, d, n-1);
printf("Move Disk-%d FROM %c TO %c\n", n, s, d);
towerOfHanoi(e, d, s, n-1);
}
}
If we run this Call this function for 3 discs (n=3) like below
towerOfHanoi('s', 'd', 'e',3);
Then the output will be
Move Disk-1 FROM s TO d Move Disk-2 FROM s TO e Move Disk-1 FROM d TO e Move Disk-3 FROM s TO d Move Disk-1 FROM e TO s Move Disk-2 FROM e TO d Move Disk-1 FROM s TO d
The actual movement of the disks will be as shown below:
Tue, 06 May 2025
Tue, 06 May 2025
Tue, 06 May 2025
Leave a comment