example4_tower_of_hanoi.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

// Function to solve the Tower of Hanoi problem
void towerOfHanoi(int n, char source, char destination, char auxiliary) {
    if (n == 1) {
        std::cout << "Move disk 1 from " << source << " to " << destination << std::endl;
        return;  // Base case: Only one disk to move
    }

    towerOfHanoi(n - 1, source, auxiliary, destination);  // Move n-1 disks from source to auxiliary
    std::cout << "Move disk " << n << " from " << source << " to " << destination << std::endl;
    towerOfHanoi(n - 1, auxiliary, destination, source);  // Move n-1 disks from auxiliary to destination
}

int main() {
    int n = 3;  // Number of disks
    towerOfHanoi(n, 'A', 'C', 'B');  // A is source, C is destination, B is auxiliary
    return 0;
}
Back to recursion