1. Introduction
The Tower of Hanoi is a classic mathematical puzzle that involves three pegs and a number of disks of different sizes. The objective is to move the entire stack of disks from one peg to another, following these simple rules:
1. Only one disk can be moved at a time.
2. A disk can only be placed on top of a larger disk.
3. A disk can be moved from the top of one stack to the top of another stack or an empty peg.
In this post, we will implement the solution to the Tower of Hanoi problem using recursion in C++.
2. Program Overview
Our Tower of Hanoi program will:
1. Define a recursive function to solve the problem.
2. Display each move made during the solution process.
3. Demonstrate the solution for a user-defined number of disks.
3. Code Program
#include<iostream>
using namespace std;
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) {
if (n == 1) {
cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod << endl;
return;
}
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl;
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}
int main() {
int n;
cout << "Enter the number of disks: ";
cin >> n;
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}
Output:
Enter the number of disks: 3 Move disk 1 from rod A to rod C Move disk 2 from rod A to rod B Move disk 1 from rod C to rod B Move disk 3 from rod A to rod C Move disk 1 from rod B to rod A Move disk 2 from rod B to rod C Move disk 1 from rod A to rod C
4. Step By Step Explanation
1. The towerOfHanoi function is a recursive function that solves the problem. When called with a single disk (n == 1), it directly moves the disk. Otherwise, it:
a. Moves the top n-1 disks from the source peg to the auxiliary peg.b. Moves the nth disk from the source peg to the destination peg.c. Finally, move the n-1 disks from the auxiliary peg to the destination peg.
2. The main function prompts the user for the number of disks and then calls the towerOfHanoi function, using rods 'A', 'B', and 'C' as a source, auxiliary, and destination pegs, respectively.
3. The recursive approach elegantly captures the essence of the problem, breaking it down into smaller subproblems until reaching the base case where the solution is straightforward.
Comments
Post a Comment
Leave Comment