Here's a C++ code to solve the Tower of Hanoi problem using recursion:
#include <iostream>
void towerOfHanoi(int n, char source, char auxiliary, char destination) {
if (n == 1) {
// Base case: If there is only one disk, move it from source to destination
std::cout << "Move disk 1 from " << source << " to " << destination << std::endl;
return;
}
// Move n-1 disks from source to auxiliary peg
towerOfHanoi(n - 1, source, destination, auxiliary);
// Move the nth disk from source to destination
std::cout << "Move disk " << n << " from " << source << " to " << destination << std::endl;
// Move the n-1 disks from auxiliary peg to destination peg
towerOfHanoi(n - 1, auxiliary, source, destination);
}
int main() {
int numDisks;
std::cout << "Enter the number of disks: ";
std::cin >> numDisks;
std::cout << "Tower of Hanoi solution:" << std::endl;
towerOfHanoi(numDisks, 'A', 'B', 'C');
return 0;
}
Output:
Enter the number of disks: 3
Tower of Hanoi solution:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Explanation:
The Tower of Hanoi problem is a classic example of recursion, where a larger problem is broken down into smaller subproblems. The recursive solution follows the concept of divide and conquer, solving the smaller subproblems and combining the solutions to solve the original problem.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|