From 87f0d3deeededb53ec9e52972650ff1482e9dbce Mon Sep 17 00:00:00 2001 From: ada-dmitry Date: Sun, 2 Apr 2023 10:49:49 +0300 Subject: [PATCH] 22 --- PL/HW/hw04.04/HanoiTower | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 PL/HW/hw04.04/HanoiTower diff --git a/PL/HW/hw04.04/HanoiTower b/PL/HW/hw04.04/HanoiTower new file mode 100644 index 0000000..1017706 --- /dev/null +++ b/PL/HW/hw04.04/HanoiTower @@ -0,0 +1,32 @@ +#include +#include +#include + +/* function to solve the Tower of Hanoi puzzle */ +void tower_of_hanoi(int n, char from, char to, char aux) +{ + /* base case - when there's only one disk present */ + if (n == 1) + { + printf("Move disk 1 from rod %c to rod %c\n", from, to); + return; + } + /* move n-1 disks from the source to auxiliary rod */ + tower_of_hanoi(n - 1, from, aux, to); + /* move the remaining one disk from the source to destination rod */ + printf("Move disk %d from rod %c to rod %c\n", n, from, to); + /* move n-1 disks from the auxiliary to destination rod */ + tower_of_hanoi(n - 1, aux, to, from); +} + +int main() +{ + int n; + /* ask user for the number of disks */ + printf("Enter the number of disks: "); + scanf("%d", &n); + /* call the tower_of_hanoi function to solve the puzzle */ + tower_of_hanoi(n, 'A', 'C', 'B'); + + return 0; +}