Towers of Hanoi
The Tower of Hanoi is a classic mathematical puzzle that involves moving a stack of disks of different sizes from one peg or tower to another. The puzzle is often used as an example of a recursive algorithm.
The game consists of three pegs and a number of disks of different sizes, which can slide onto any peg. The puzzle starts with the disks in a neat stack in ascending order of size on one peg, the smallest at the top, thus forming a conical shape.
The objective of the puzzle is to move the entire stack to another peg, 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 or on an empty peg.
No disk may be placed on top of a smaller disk.
The puzzle is named after the city of Hanoi in Vietnam, where it was invented. It is often used in computer science courses to teach algorithmic thinking and recursion.
Figure - Tower of Hanoi- Shifting disk from pole A to C [1][1] https://media.geeksforgeeks.org/wp-content/uploads/tower-of-hanoi.png
/* Write a C program to create tower of hanoi by using stack */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <stack>
using namespace std;
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;
}
Comments
Post a Comment