Complementary task for topic: 10

M Nemeth · 2023-08-29 15:21:04.633218'

Recursion: Hanoi tower

Recursion: Hanoi tower

HARD!
Write a program to solve the Tower of Hanoi puzzle using recursion. The Tower of Hanoi is a classic mathematical puzzle where you have three pegs and a set of disks of different sizes. The objective is to move all the disks from the first peg to the third peg following these rules:
Only one disk can be moved at a time.
A larger disk cannot be placed on top of a smaller disk.

Hint:

Solution
#include 

// Function to move a disk from source peg to destination peg
void moveDisk(char source, char destination) {
    printf("Move disk from %c to %c\n", source, destination);
}

// Function to solve the Tower of Hanoi puzzle using recursion
void towerOfHanoi(int numDisks, char source, char auxiliary, char destination) {
    if (numDisks == 1) {
        moveDisk(source, destination);
        return;
    }

    towerOfHanoi(numDisks - 1, source, destination, auxiliary);
    moveDisk(source, destination);
    towerOfHanoi(numDisks - 1, auxiliary, source, destination);
}

int main() {
    int numDisks;
    printf("Enter the number of disks in the Tower of Hanoi puzzle: ");
    scanf("%d", &numDisks);

    if (numDisks <= 0) {
        printf("Error: The number of disks should be greater than 0.\n");
        return 1;
    }

    printf("Steps to solve the Tower of Hanoi puzzle with %d disks:\n", numDisks);
    towerOfHanoi(numDisks, 'A', 'B', 'C');

    return 0;
}



Explanation
    The main function prompts the user to enter the number of disks in the Tower of Hanoi puzzle.
    The user inputs the number of disks, and the program reads it using scanf.
    The main function then calls the towerOfHanoi function, passing the number of disks and the three pegs ('A', 'B', 'C') as arguments.
    The towerOfHanoi function uses recursion to solve the Tower of Hanoi puzzle. If there's only one disk, it simply moves the disk from the source peg to the destination peg. Otherwise, it moves the top (n-1) disks from the source peg to the auxiliary peg using recursion, then moves the largest disk from the source peg to the destination peg, and finally moves the (n-1) disks from the auxiliary peg to the destination peg using recursion.
    Each move is printed with the source peg and destination peg in the moveDisk function, which is called when a disk is moved.
< < previous    next > >