Tower Of Hanoi Algorithm

The Tower of Hanoi Algorithm is a classic puzzle-solving problem which was first introduced by the French mathematician Edouard Lucas in 1883. The problem consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus forming a conical shape. The objective of the puzzle is to move the entire stack to another rod, 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 rod, and no disk may be placed on top of a smaller disk. The Tower of Hanoi algorithm is widely used in computer science and mathematics to teach recursion and to model complex problems in areas such as artificial intelligence and data storage management. Solving the Tower of Hanoi puzzle can be approached through a recursive algorithm, which breaks the problem down into smaller subproblems until the base case is reached. The base case for this algorithm is when there is only one disk to be moved directly to the destination rod. For more than one disk, the algorithm moves n-1 disks to an intermediate rod, moves the largest disk to the destination rod, and then moves the n-1 disks from the intermediate rod to the destination rod. This process is recursively repeated until the entire stack is transferred to the destination rod. The minimal number of moves required to solve a Tower of Hanoi puzzle with n disks is 2^n - 1, showcasing the exponential growth in complexity as the number of disks increases. The Tower of Hanoi algorithm not only provides an elegant solution to the puzzle but also serves as a powerful tool for understanding and solving a wide range of real-world problems.

#include <stdio.h>
#include <stdlib.h>

// Function for Tower of Hanoi algorithm 
void hanoi(int noOfDisks,char where,char to,char extra){
	if(noOfDisks == 0 )
	{
		return;
	}
	else
	{
		hanoi(noOfDisks-1, where, extra , to);
		printf("Move disk : %d from %c to %c\n",noOfDisks,where,to);
		hanoi(noOfDisks-1,extra,to,where);
	}
}
int main(void){
	int noOfDisks;
	
	//Asks the number of disks in the tower 
	printf("Number of disks: \n");
	scanf("%d", &noOfDisks);
	
	hanoi(noOfDisks,'A','B','C');
	
	return 0;

}

LANGUAGE:

DARK MODE: