1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> using namespace std; // Function to solve the Tower of Hanoi puzzle void towerOfHanoi(int n, char fromRod, char toRod, char auxRod) { if (n == 1) { cout << "Move disk 1 from rod " << fromRod << " to rod " << toRod << endl; return; } towerOfHanoi(n - 1, fromRod, auxRod, toRod); cout << "Move disk " << n << " from rod " << fromRod << " to rod " << toRod << endl; towerOfHanoi(n - 1, auxRod, toRod, fromRod); } int main() { int n; cout << "Enter the number of disks: "; cin >> n; cout << "The sequence of moves to solve the Tower of Hanoi puzzle is:" << endl; towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods return 0; } |
Explanation
- Tower of Hanoi Function:
towerOfHanoi(int n, char fromRod, char toRod, char auxRod)
Advertisement- Parameters:
n
: The number of disks to move.fromRod
: The rod from which the disks are moved.toRod
: The rod to which the disks are moved.auxRod
: The auxiliary rod used in the process.
Advertisement - Base Case: If
n
is 1, it simply moves the disk fromfromRod
totoRod
. - Recursive Steps:
- Move
n-1
disks fromfromRod
toauxRod
usingtoRod
as auxiliary. - Move the nth disk from
fromRod
totoRod
. - Move the
n-1
disks fromauxRod
AdvertisementtoRod
usingfromRod
as auxiliary.
- Move
- Parameters:
- Main Function:
- The
main()
function prompts the user to enter the number of disks. - It then calls
towerOfHanoi()
with the initial rods ('A'
,'B'
,'C'
) representing the source, auxiliary, and destination rods, respectively.
- The