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

2019/7/10 22:42:26

本文主要是介绍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++ 实现汉诺塔的实例详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程