-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhanoi_tower_test.cpp
63 lines (53 loc) · 1.33 KB
/
hanoi_tower_test.cpp
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <cstdio>
#include <conio.h>
#include <cmath>
#include <cassert>
using namespace std;
/**
** 源文件: hanoi_tower_test.cpp
** 功能说明:
** 测试程序,汉若塔的计算(搬运次数)与演示搬运过程。
** 作者:junkun huang e-mail:[email protected]
** 创建日期:2008-11 /
*/
int loop_num = 0;
unsigned move(char x, int n, char z)
{
cout << x << "->" << z <<"; ";
loop_num++;
return 1;
}
unsigned hanoi(int n, char x, char y, char z)
{
/// 因为该函数递归调用的频率会很高所有,若在函数内定义变量move_times那么就加大了,函数的递归代价;
/// 若使用外面变量记录搬运次数,减轻递归负担,但降低耦合度。
/// 需要程序设计者自行取舍。
unsigned move_times = 0;
if(n == 1)
move_times += move(x, 1, z);
else
{
move_times += hanoi(n-1, x, z, y);
move_times += move(x, n, z);
move_times += hanoi(n-1, y, x, z);
}
return move_times;
}
int main()
{
char c;
do
{
char x = 'A',y = 'B', z = 'C';
loop_num = 0;
int hanoi_num;
cout <<" 请输入汉诺塔上的盘子数目:";
cin >> hanoi_num;
hanoi(hanoi_num, x, y, z);
cout << "\n\n搬运次数:" << loop_num << endl;
cout << " !!!按任意键继续,Esc退出程序!!!" << endl;
}while( (c=getch())!=27 );
return 0;
}