C++ 递归实现汉诺塔
C++实现汉诺塔
#include <iostream> using namespace std; void move(int n,char x,char y,char z) { if(n==1) { cout<<x<<"--->"<<z<<endl; } else { move(n-1,x,z,y); cout<<x<<"--->"<<z<<endl; move(n-1,y,x,z); } } void m(int n,char c1,char c2,char c3) { if(n==1) { cout<<c1<<"------------------>"<<c3<<endl; } else { m(n-1,c1,c3,c2); cout<<c1<<"------------------>"<<c3<<endl; m(n-1,c2,c1,c3); } } int main() { int a; char x1='X';char x2='Y';char x3='Z'; cout<<"请输入汉罗塔的层数:"<<endl; cin>>a; cout<<"移动步骤日下:"<<endl; move(a,x1,x2,x3); //m(a,x1,x2,x3); return 0; }
A man must be on his own!