Hanoi塔问题

来源:互联网 发布:ubuntu下apache 2配置 编辑:程序博客网 时间:2024/06/08 07:45
//-----------------------Hanoi.cpp-----------------------------#include<iostream>#include<iomanip>using namespace std;void move(unsigned n,unsigned & moveNumber,char sourse,char destination,char spare);int main(){const char PEG1='A',           PEG2='B',   PEG3='C';unsigned moveNumber=0;cout<<"This program solves the Hanio Towers puzzle.\n\n";cout<<"Enter the number of disks: ";int numDisks;cin>>numDisks;cout<<endl;move(numDisks,moveNumber,PEG1,PEG2,PEG3);system("pause");}void move(unsigned n,unsigned & moveNumber,char source,char destination,char spare){if(n==1){moveNumber++;cout<<setw(3)<<moveNumber<<". Move the top disk from "<<source<<" to "<<destination<<endl;}else{move(n-1,moveNumber,source,spare,destination);move(1,moveNumber,source,destination,spare);move(n-1,moveNumber,spare,destination,source);}}

This program solves the Hanio Towers puzzle.Enter the number of disks: 4  1. Move the top disk from A to C  2. Move the top disk from A to B  3. Move the top disk from C to B  4. Move the top disk from A to C  5. Move the top disk from B to A  6. Move the top disk from B to C  7. Move the top disk from A to C  8. Move the top disk from A to B  9. Move the top disk from C to B 10. Move the top disk from C to A 11. Move the top disk from B to A 12. Move the top disk from C to B 13. Move the top disk from A to C 14. Move the top disk from A to B 15. Move the top disk from C to B请按任意键继续. . .