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

2025-05-27 0 30

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

前言:

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

要求:

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

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

实现代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35
#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;

}

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C++ 实现汉诺塔的实例详解 https://www.kuaiidc.com/72428.html

相关文章

发表评论
暂无评论