For example if I use 4 disks, The problem should be solved in 3 steps according to the equation. However, mine takes 9 steps. Why is it so?
Consider the code here
include <stdio.h>
void towerOfHanoi(int n, char from_rod, char to_rod,
char aux_rod1, char aux_rod2)
{
if (n == 0)
return;
if (n == 1) {
printf("\n Move disk %d from rod %c to rod %c",
n, from_rod, to_rod);
return;
}
towerOfHanoi(n - 2, from_rod, aux_rod1, aux_rod2,
to_rod);
printf("\n Move disk %d from rod %c to rod %c ",
n - 1, from_rod, aux_rod2);
printf("\n Move disk %d from rod %c to rod %c ",
n, from_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c ",
n - 1, aux_rod2, to_rod);
towerOfHanoi(n - 2, aux_rod1, to_rod, from_rod,
aux_rod2);
}
// driver program
int main()
{
int n = 4; // Number of disks
// A, B, C and D are names of rods
towerOfHanoi(n, 'A', 'D', 'B', 'C');
return 0;
}
When you have 4 pegs,time complexity to move 1 peg will require 1 comparison. time complexity to move 2 peg will require 3 comparisons. Time complexity = 2*T(n-2) + 3 ,n>=3
While solving it through substitution method . T(n) = 2*T(n-2) + 3 ,n>=3
= 2^2T(n-4) + 2*3 + 3 = 2^3T(n-6) + 2^2*3 + 2*3 + 3 and so on.
for kth substitution,
=2^(k/2)*T(nk) + 2^(k/2 -1 )*3 + ..... + 2^2*3 + 2*3 + 3 ---- eqn_(1)
take nk=2 => k=n-2 so eqn_(1) becomes = 2^(n/2 -1)*3 + 2^(n/2 - 2).3 + .....+ 2^2*3 + 2*3 + 3
= 3{1.(2^(n/2) - 1)}
= θ(2^(n/2))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.