I am having a difficult time grasping the logic behind the Tower of Hanoi recursion function.
How is it possible that the function when it calls itself is able to move n-1 disks, when only 1 disk is allowed to move at a time?
So if n = 3, then 2 disks move from one peg to the other? Could someone break it down for me?
1 2 3 4 5 6 7 8 9
void towers(int n, char a, char b, char c){
if (n > 0)
{
towers(n - 1, a, c, b);
cout << "Move from " << a << " to " << b << endl;
towers(n - 1, c, b, a);
}
}
1. Take a piece of paper, draw three circles representing the bases of the towers and mark them from left to right as "a", "b" and "c".
2. Build a tower of Hanoi on "a" with f.e. three coins of different diameter.
3. Now be a CPU and do step by step exactly what your program does command you.
I believe my confusion comes in the syntax. When I run this code the output (from n=3) that is shown is this:
1 2 3 4 5 6 7
Move from a to b
Move from a to c
Move from b to c
Move from a to b
Move from c to a
Move from c to b
Move from a to b
The line of code: towers(n-1, a, c, b) means to me that (n-1) disks moves from a to b.
But then doesn't the next output shows a Move from a to c, I don't follow why that is based on the code that is written.
Could you explain @tcs?