/* ************************************************************************** * Program name : 028_Tower_of_Hanoi (Version 1.00) * * Author : Duck Wong * * Language : C / C++ * * Compiler : Boodshed Dec-C++ compiler Ver 3.95 * * Computer : PII350 * * O/S : Windows 98 * ************************************************************************** * Version 1.00 : 2000/06/12 - first version * ************************************************************************** * Description : (a) Input the number of disks * * (b) Output the steps * * (c) Try again ? * ************************************************************************** */ #include #include void hanoi (char peg1, char peg2, char peg3, int disks); // Note (1) int main() { // part 1 : declaration int disks; char peg1 = 'A', // origin peg2 = 'B', // destination peg3 = 'C', // spare Again; // run this program again do { // part 2 : Repeat asking the number of disks do { cout << "\nEnter the number of disks : "; cin >> disks; } while (disks<=0); // part 3 : Call the function hanoi hanoi(peg1, peg2, peg3, disks); // part 4 : try again ? cout << "\n\n\aTry again (Y/N) : "; cin >> Again; cout << "\n"; } while (Again=='Y' || Again=='y'); cout << "\n" << endl; system("PAUSE"); return 0; } void hanoi (char p1, char p2, char p3, int disks) { if (disks==1) { cout << "\n\tMove top disk from peg_" << p1 << " to peg_" << p2 <<"."; return; } // Move (n-1) disks from peg1 to peg3 hanoi(p1, p3, p2, disks-1); // Move the last disk from peg1 to peg2 cout << "\n\tMove top disk from peg_" << p1 << " to peg_" << p2 <<"."; // Move (n-1) disks from peg3 to peg2 hanoi(p3, p2, p1, disks-1); } /* Notes (1) Let us assume that the aim is moving all disks from peg1 to peg2. Moving n disks can be viewed in terms of moving only (n-1( disks as follows : (a) Move (n-1) disks from peg1 to peg3 (b) Move the last disk from peg1 to peg2 (c) Move (n-1) disks from peg3 to peg2 To solve this program, the hanoi function needs 4 parameters : (a) The peg on which these disks are initially threaded (b) The peg to which this stack of disks is to be moved (c) The peg to be used as a temportary holding area */