欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

C++ 实现汉诺塔的实例详解

来源:本站原创|时间:2020-01-10|栏目:C语言|点击:

C++ 实现汉诺塔的实例详解

前言:

有A,B,C三塔,N个盘(从小到大编号为1-N)起初都在A塔,现要将N个盘全部移动到C塔(按照河内塔规则),求最少移动次数以及每次的移动详细情况。

要求:

需要采用递归方法和消除尾递归两种方法编写。

盘数N由用户从标准输入读入,以一个整数表示,然后请调用两个方法按照下面例子所述分别在屏幕中输出结果(正常情况下一个输入数据会显示同样的输出结果2次)。

实现代码:

#include<iostream>
using namespace std;
void move(int count,char start='a',char finish='b',char temp='c')
{
 if(count>0)
 {
  move(count-1,start,temp,finish);
 cout<<"Move "<<count<<" from "<<start<<" to "<<finish<<endl;
 move(count-1,temp,finish,start);
 }
}
void move_without_recursion(int count,char start='a',char finish='b',char temp='c')
{
 char swap;
 while(count>0)
 {
  move_without_recursion(count-1,start,temp,finish);
 cout<<"Move "<<count<<" from "<<start<<" to "<<finish<<endl;
 count--;
 swap=start;
 start=temp;
 temp=swap;
 }
}
int main()
{
 int count;
 cout<<"please enter the number:";
 cin>>count;
 cout<<"递归方法运行过程:"<<endl;
  move(count);
  cout<<"消除尾递归方法运行过程:"<<endl;
  move_without_recursion(count);
return 0;
}


如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:C语言数据结构之顺序数组的实现

栏    目:C语言

下一篇:C++ 哈夫曼树对文件压缩、加密实现代码

本文标题:C++ 实现汉诺塔的实例详解

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/1230.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有