关于C++,hanoi塔的递归问题一直是个经典问题,我们学习数据结构的时候也会时常用到, 因为它的时间复杂度和空间复杂度都很高,我们在实际的应用中不推荐使用这种算法,移动n个盘子, 需要2的n次幂减一步,例如:5个盘子,31步;10个盘子,1023步。 下面,是我整理的有关C++递归的代码实现过程,希望对大家的学习有所帮助。 #include <iostream> using namespace std; //第一个塔为初始塔,中间的塔为借用塔,最后一个塔为目标塔 int step=1;//记录步数 void move(int n,char from,char to) //将编号为n的盘子由from移动到to { cout<<"第 "<<step++<<" 步:将"<<n<<"号盘子"<<from<<"--------"<<to<<endl; } void hanoi(int n,char from,char denpend_on,char to)//将n个盘子由初始塔移动到目标塔(利用借用塔) { if (n==1) move(1,from,to);//只有一个盘子是直接将初塔上的盘子移动到目的地 else { hanoi(n-1,from,to,denpend_on);//先将初始塔的前n-1个盘子借助目的塔移动到借用塔上 move(n,from,to); //将剩下的一个盘子移动到目的塔上 hanoi(n-1,denpend_on,from,to);//最后将借用塔上的n-1个盘子移动到目的塔上 } } int main() { cout<<"请输入盘子的个数:"<<endl; int n; scanf("%d",&n); char x='A',y='B',z='C'; cout<<"盘子移动过程如下:"<<endl; hanoi(n,x,y,z); return 0;
|