65,187
社区成员




please input you number of the disk on the peg A:1
Move top disk from A peg to C peg
请按任意键继续. . .
please input you number of the disk on the peg A:2
Move top disk from A peg to B peg
Move top disk from A peg to C peg
Move top disk from B peg to C peg
请按任意键继续. . .
please input you number of the disk on the peg A:3
Move top disk from A peg to C peg
Move top disk from A peg to B peg
Move top disk from C peg to B peg
Move top disk from A peg to C peg
Move top disk from B peg to A peg
Move top disk from B peg to C peg
Move top disk from A peg to C peg
请按任意键继续. . .
please input you number of the disk on the peg A:4
Move top disk from A peg to B peg
Move top disk from A peg to C peg
Move top disk from B peg to C peg
Move top disk from A peg to B peg
Move top disk from C peg to A peg
Move top disk from C peg to B peg
Move top disk from A peg to B peg
Move top disk from A peg to C peg
Move top disk from B peg to C peg
Move top disk from B peg to A peg
Move top disk from C peg to A peg
Move top disk from B peg to C peg
Move top disk from A peg to B peg
Move top disk from A peg to C peg
Move top disk from B peg to C peg
请按任意键继续. . .
#include <iostream>
#include <string>
using namespace std;
void Hanoi(int n,string & A, string & B,string & C);//move the disks from A to C with the help of B
void main(){
int n;
string a("A peg");//A 柱
string b("B peg");//B 柱
string c("C peg");//c 柱
cout<<"please input you number of the disk on the peg A:";
cin>>n;
Hanoi(n,a,b,c);
}
void Hanoi(int n,string & A, string & B,string & C){
if(n==1) cout<<"Move top disk from "<<A<<" to "<<C<<endl;
else {
Hanoi(n-1,A,C,B);//move the n-1 disks from A to B with the help of C
cout<<"Move top disk from "<<A<<" to "<<C<<endl;
Hanoi(n-1,B,A,C);//move the n-1 disks from B to C with the help of A
}
}