Solving Tower of Hanoi problem with n disks
The
Tower
of Hanoi
problem is a classic example of recursion and stack operations. The
goal is to move n
disks from the source peg to the destination peg, using an auxiliary
peg, while obeying the following rules:
Explanation:
Function
tower(n,
from, aux, to)
:
Moves
n
disks fromfrom
peg toto
peg usingaux
peg.Recursively breaks the problem into smaller moves:
Move
n-1
disks fromfrom
→aux
Move the largest disk (
n
) fromfrom
→to
Move
n-1
disks fromaux
→to
main()
function:
Takes the number of disks (
n
) as input.Calls
tower()
to print all moves.Calculates total moves using formula
2^n - 1
withpow()
.
ERROR?
You're
getting this error because the pow()
function (used to calculate total moves) is part of the math
library, and
the math library (libm
)
is not linked
by default in
GCC.
To Fix This:
Use the -lm
flag at the end of your gcc
command to link the math library.
gcc han.c -o abcd -lm
Why?
pow()
is defined in the<math.h>
header but implemented in the math library.You must explicitly link it using
-lm
.
Re-run Your Program:
After compiling successfully:
./abcd
Let me know if you want a version of the program that avoids using
pow()
entirely (using just integer
math).
Program:
#include
<stdio.h>
#include
<math.h>
//
Recursive function to solve Tower of Hanoi
void
tower(int n, char from_peg, char aux_peg, char to_peg) {
if
(n == 1) {
printf("Move
disk %d from %c peg to %c peg\n", n, from_peg, to_peg);
return;
}
//
Move n-1 disks from source to auxiliary
tower(n
- 1, from_peg, to_peg, aux_peg);
//
Move the nth disk to destination
printf("Move
disk %d from peg %c to %c peg\n", n, from_peg, to_peg);
//
Move n-1 disks from auxiliary to destination
tower(n
- 1, aux_peg, from_peg, to_peg);
}
int
main() {
int
n;
printf("Enter
the number of disks: ");
scanf("%d",
&n);
tower(n,
'A', 'B', 'C'); // A: source, B: auxiliary, C: destination
printf("Total
number of moves = %.0f\n", pow(2, n) - 1);
return
0;
}
OUTPUT:
No comments:
Post a Comment