#include <iostream> #include <vector> using namespace std; const int TOTALNUM=5; int disknum[4]={TOTALNUM,0,0,0}; int pos[4][TOTALNUM]={0}; int fixbase=2; void fourPegHonoi(int diskCount,char src,char temp1 , char temp2,char dest); void threePegHonoi(int diskCount,char src,char temp ,char dest); void move(char src, char dest); void print(); bool check(); int main(int argc, char* argv[]) { int i=0; for(i=0;i<TOTALNUM;++i) pos[0][i]=TOTALNUM-i; print(); fourPegHonoi(TOTALNUM,'a','b','c','d'); print(); return 0; } void fourPegHonoi(int diskCount,char src,char temp1 , char temp2,char dest) { cout<<"begin of fourPegHonoi("<<diskCount <<","<<src <<","<<temp1 <<","<<temp2 <<","<<dest<<")"<<endl; if (diskCount>fixbase) { fourPegHonoi(diskCount-fixbase,src,temp1,dest,temp2); threePegHonoi(fixbase,src,temp1,dest); fourPegHonoi(diskCount-fixbase,temp2,src,temp1,dest); } else if (diskCount<=fixbase && diskCount>0) threePegHonoi(diskCount,src,temp1,dest); cout<<"end of fourPegHonoi("<<diskCount <<","<<src <<","<<temp1 <<","<<temp2 <<","<<dest<<")"<<endl; } void threePegHonoi(int diskCount,char src,char temp ,char dest) { cout<<"begin of threePegHonoi("<<diskCount <<","<<src <<","<<temp <<","<<dest<<")"<<endl; if (diskCount>1) { threePegHonoi(diskCount-1,src,dest,temp); move(src,dest); threePegHonoi(diskCount-1,temp,src,dest); } else if (diskCount==1) move(src,dest); cout<<"end of threePegHonoi("<<diskCount <<","<<src <<","<<temp <<","<<dest<<")"<<endl; } void move(char src, char dest) { check(); cout<<"Move top disk from peg "<<src<<" to peg "<<dest<<endl; int srcindex=src-'a'; int destindex=dest-'a'; if (disknum[srcindex]<1 || disknum[destindex]>=TOTALNUM) { cout<<"num error"<<endl; exit(-1); } pos[destindex][disknum[destindex]]=pos[srcindex][disknum[srcindex]-1]; pos[srcindex][disknum[srcindex]-1]=0; check(); --disknum[srcindex]; ++disknum[destindex]; print(); } void print() { int i,j; for(i=0;i<TOTALNUM;++i) { for (j=0;j<4;++j) { int index=TOTALNUM-i-1; if (pos[j][index]>0) cout<<pos[j][index]; else cout<<' '; cout<<' '; } cout<<endl; } for(i=0;i<4;++i) cout<<(char)('a'+i)<<' ' ; cout<<endl; cout<<"disknum:"<<endl; for(i=0;i<4;++i) cout<<disknum[i]<<' ' ; cout<<endl; cout<<endl; cout<<endl; } bool check() { int i,j; for (i=0; i<3;++i) for(j=0;j<TOTALNUM-1;++j) if (pos[i][j]<pos[i][j+1]) { cout<<"pos error"<<endl; exit(-1); } return true; }
vc6下编译并运行通过