C++ - Tower of Hanoi Program

The Tower of Hanoi is a famous challenge that has captivated computer scientists, mathematicians, and puzzle fans for decades. The problem is simple to understand, but it takes some thought to solve optimally. In this blog article, we will go into the Tower of Hanoi problem, investigate the recursive solution, and present a C++ implementation.

#include

using namespace std;

void tower_Of_Hanoi(int n, char source, char destination, char auxiliary) {

    // Base case: If there's only one disk, move it from source to destination

    if (n == 1) {

        cout << "Move disk 1 from " << source << " to " << destination << endl;

        return;

    }

    // Move n-1 disks from source to auxiliary, using destination as a buffer

    tower_Of_Hanoi(n - 1, source, auxiliary, destination);   

    // Move the nth disk from source to destination

    cout << "Move disk " << n << " from " << source << " to " << destination << endl;    

    // Move the n-1 disks from auxiliary to destination, using source as a buffer

    tower_Of_Hanoi(n - 1, auxiliary, destination, source);

}

int main() {

    int n; // Number of disks

    cout << "Enter the number of disks: ";

    cin >> n;

    // Call the tower_Of_Hanoi function

    tower_Of_Hanoi(n, 'A', 'C', 'B'); // A, B, and C are names of rods

    return 0;

}

Explanation of the Code

  • Tower of Hanoi function: This function is at the heart of the software. It requires four parameters: the number of disks n, the source rod, the destination rod, and the auxiliary rod. The function is recursive and follows the reasoning described above.
  • Base Case: If n == 1, the function simply moves the disk from its source to its destination. This is the simplest move.
  • Recursive Calls: The function initially sends n-1 disks from the source to the auxiliary rod. It then transports the largest disk from source to destination. Finally, it transports the n-1 disks from the auxiliary rod to their destination.
  • Main Function: The main function accepts the user's input for the number of disks and calls the tower_Of_Hanoi function to conduct the appropriate moves.