lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

[c/cpp]:递归算法:汉诺塔问题代码

 

 

 

 

一、代码

 1 #include <iostream>
 2 
 3 
 4 using namespace std;
 5 
 6 
 7 // plate_numbers=n;
 8 // from_stick=from;
 9 // target_stick=to;
10 // assistant_stick=assistant;
11 void hanoi(int n, char from, char to, char assistant)
12 {
13     if (n==1) {
14         cout << "\t[move]:" << n    << ",\t" ;
15         cout << "[from]:"   << from << ",\t" ;
16         cout << "[to]:"     << to   << endl  ;
17         return ;
18     }
19     // move_from:from; move_to:assistant;  move_assistant:to
20     hanoi(n-1, from, assistant, to);
21         cout << "\t[move]:" << n    << ",\t" ;
22         cout << "[from]:"   << from << ",\t" ;
23         cout << "[to]:"     << to   << ",\t" ;
24         cout << "[assistant]:" << assistant << endl;
25     // move_from:assistant;  move_to:to,  move_assistant:from
26     hanoi(n-1, assistant, to, from);
27 }
28 
29 
30 //
31 int main(int argc, char *argv[], char *envp[])
32 {
33     
34     hanoi(3, 'F', 'T', 'A');
35     
36     return 0;
37 }

 

 

 

 二、运行结果

	[move]:1,	[from]:F,	[to]:T
	[move]:2,	[from]:F,	[to]:A,	[assistant]:T
	[move]:1,	[from]:T,	[to]:A
	[move]:3,	[from]:F,	[to]:T,	[assistant]:A
	[move]:1,	[from]:A,	[to]:F
	[move]:2,	[from]:A,	[to]:T,	[assistant]:F
	[move]:1,	[from]:F,	[to]:T

 

 

 

三、参考资料:

 

  1、  「递归」是检验编程天赋的试金石(神级教程)  -  https://www.bilibili.com/video/BV1LiS1YSEgF/?vd_source=bef44438dcfc47fc71532258ae4beac7

 

  2、  c++在线编译工具  -  https://coliru.stacked-crooked.com/

 

posted on 2024-11-08 05:53  lnlidawei  阅读(4)  评论(0编辑  收藏  举报