Solve the Tower of Hanoi problem.void TowerOfHanoi(unsigned int n, char from_peg, char to_peg, char aux_peg)
{
// Bad input
if (n == 0)
return;
// Base case, move disk 1 to the destination peg
if (n == 1)
{
cout << "Move disk " << n << " from tower " << from_peg << " to tower " << to_peg << endl;
return;
}
// The goal is to move all disks on top of the biggest disk, N, to the auxiliary peg,
// move disk N to destination peg then move the disks placed on the spare peg to
// destination peg, on top of disk N. We do these three steps recursively.
// Step 1 - Move Disks 1 to N -1 disks (smaller tower) to the auxiliary peg, using destination as auxiliary peg
TowerOfHanoi(n - 1, from_peg, aux_peg, to_peg);
// Step 2 - Move Disk N from the source peg to destination peg
cout << "Move disk " << n << " from tower " << from_peg << " to tower " << to_peg << endl;
// Step 3 - Move what is left on the auxiliary peg to destination peg, using source peg as auxiliary peg
TowerOfHanoi(n - 1, aux_peg, to_peg, from_peg);
} |