Tower of Hanoi Problem
C++
Hard
5 views
Problem Description
Move disks from one rod to another following rules.
Real Life: Classic recursion puzzle teaching problem-solving.
Step-by-Step Logic:
1. Move n-1 disks from source to auxiliary
2. Move largest disk from source to destination
3. Move n-1 disks from auxiliary to destination
4. Each step is recursive
Official Solution
void towerOfHanoi(int n, char from, char to, char aux) {
if(n == 1) {
cout << "Move disk 1 from " << from << " to " << to << endl;
return;
}
towerOfHanoi(n - 1, from, aux, to);
cout << "Move disk " << n << " from " << from << " to " << to << endl;
towerOfHanoi(n - 1, aux, to, from);
}
void function_q14_tower_hanoi() {
int disks = 3;
cout << "Steps to solve Tower of Hanoi with " << disks << " disks:" << endl;
towerOfHanoi(disks, 'A', 'C', 'B');
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!