In: Computer Science
In Lecture 5, we discussed how to solve the Tower of Hanoi problem (Exercise 5.36 in the textbook). Consider the following problem variant in which one extra constraint has been added: There are three pegs and n disks of different sizes. Initially, all disks are on the leftmost peg and arranged in order of decreasing size, with the smallest disk on top. The task is to move all the disks to the rightmost peg, under the constraints that: • Only one disk can be moved in each step; • Direct moves between the leftmost peg and the rightmost peg are not allowed; and • A larger disk may never be placed on top of a smaller disk. Write a C program that asks for a positive integer n and then outputs a valid sequence of moves that completes the above task. You may take the source code for solving the original problem presented during the lecture (available via Blackboard) as a starting point for your program.
Code:
#include <stdio.h>
void towerOfHanoi(int n, char peg_from, char peg_to, char
peg_aux)
{
if (n == 1)
{
printf("\nMove disk 1 from rod %c
to rod %c", peg_from, peg_to);
return;
}
towerOfHanoi(n-1, peg_from, peg_aux, peg_to);
printf("\nMove disk %d from rod %c to rod %c", n,
peg_from, peg_to);
towerOfHanoi(n-1, peg_aux, peg_to, peg_from);
}
int main()
{
int n;
printf("Enter a positive integer : ");
scanf("%d",&n);
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are
names of pegs
return 0;
}
Please refer to the screenshot of the code to understand the indentation of the code:
Output:
1.
2.
For any doubts or questions comment below.