#include using namespace std; void hanoi( char peg1, char peg2, char peg3, int how_many ); int main() { char peg1 = 'A', // origin peg2 = 'B', // destination peg3 = 'C'; // spare int how_many; // number of disks initially on the origin // Prompt for and warn about // the number of disks to be moved. cout << "\nHow many disks initially on peg A?" << "\nIf more than 7, the solution may seem to " << "take forever! "; cin >> how_many; cout << endl << endl; // Anything to move? if ( how_many < 1 ) cout << "There's nothing to move!" << endl; // Otherwise solve with: // -- peg1 as the origin // -- peg2 as the destination // -- peg3 as the spare else hanoi( peg1, peg2, peg3, how_many ); return 0; } // p1 -- origin // p2 -- destination // p3 -- spare // how_many -- number of disks to move void hanoi( char p1, char p2, char p3, int how_many ) { // If there is only 1 disk on p1, then move it to p2 // and quit as the problem is solved. if ( how_many == 1 ) { cout << "Move top disk from peg " << p1 << " to peg " << p2 << endl; return; } // Otherwise: // (1) Move how_many - 1 disks from p1 to p3: // p1 is the origin, p3 is the destination, // and p2 is the spare. // // (2) Move the top disk from p1 to p2. // // (3) Move how_many - 1 disks from p3 to p2: // p3 is the origin, p2 is the destination, // and p1 is the spare. hanoi( p1, p3, p2, how_many - 1 ); cout << "Move top disk from peg " << p1 << " to peg " << p2 << endl; hanoi( p3, p2, p1, how_many - 1 ); }