Hi there,
I have been trying to figure out the common recursion problem given in e.g. 6.42 in the following link: Towers of Hanoi. After a few hours I still can't figure it out, even though I've got the code:
#include <iostream>
using namespace std;
// num disks
void Towers(int numToMove, int initialPeg, int finalPeg, int holdingPeg)
{
// 1, 3, 2
if(numToMove == 1)
{
cout << initialPeg << "->" << finalPeg << endl;
}
else if(numToMove > 1)
{
Towers(numToMove - 1, initialPeg, holdingPeg, finalPeg); // 1, 2, 3
cout << initialPeg << "->" << finalPeg << endl;
Towers(numToMove - 1, holdingPeg, finalPeg, initialPeg); // 3, 2, 1
}
}
int main()
{
Towers(3, 1, 3, 2); // move stack from peg 1 to 3, using peg 2 as holding peg
return 0;
}
Can someone please explain how this works. I just don't get it, even though e.g. 6.42 pretty much explained how :P