所以我想计算调用函数moveSingleDisk()的时间,但我似乎无法弄清楚...使用此代码:
#include <iostream>
using namespace std;
void moveTower(int n, char start, char finish, char temp, int count);
void moveSingleDisk(char moveFrom, char moveTo, int count);
void calcHanoi(int n);
int main (int argc, const char * argv[])
{
calcHanoi(5);
return 0;
}
void calcHanoi(int n)
{
int count = 0;
moveTower(n, 'A', 'B', 'C', count);
}
void moveTower(int n, char start, char finish, char temp, int count)
{
if (n == 1)
{
count++;
moveSingleDisk(start, finish, count);
return;
}
moveTower(n-1, start, temp, finish, count);
count++;
moveSingleDisk(start, finish, count);
moveTower(n-1, temp, finish, start, count);
}
void moveSingleDisk(char moveFrom, char moveTo, int count)
{
cout << count << ": " << moveFrom << " -> " << moveTo << endl;
}
我得到以下输出:
1: A -> B
1: A -> C
2: B -> C
1: A -> B
2: C -> A
2: C -> B
3: A -> B
1: A -> C
2: B -> C
2: B -> A
3: C -> A
2: B -> C
3: A -> B
3: A -> C
4: B -> C
1: A -> B
2: C -> A
2: C -> B
3: A -> B
2: C -> A
3: B -> C
3: B -> A
4: C -> A
2: C -> B
3: A -> B
3: A -> C
4: B -> C
3: A -> B
4: C -> A
4: C -> B
5: A -> B
我试图追踪这个问题,但是递归使得跟踪这类事情非常困难(至少对我来说)。
非常感谢任何帮助或解释!谢谢:))
答案 0 :(得分:3)
如果您只需要调用moveSingleDisk
,请在moveSingleDisk
static int count = 0;
count++;
看一下这个例子,你不需要传递计数器参数
#include <iostream>
using namespace std;
int f(){
static int i = 0;
cout << i++;
return i < 5 ? f() : 5;
}
int main(){
f();
return 0;
}
答案 1 :(得分:2)
您按值传递count
,因此对moveTower
的递归调用不会修改它的本地副本。通过引用传递:
void moveTower(int n, char start, char finish, char temp, int & count)
^
在moveSingleDisk
内增加计数器可能会稍微简洁,而不是在每次调用之前,所以你可以确定不会错过任何调用。在这种情况下,您还需要通过引用传递。
答案 2 :(得分:1)
使用递归数据/算法,一种功能方法可以简化代码:从递归函数返回计数,“聚合”嵌套级别。但是这样你就会失去“步数”的显示。
int moveTower(int n, char start, char finish, char temp);
int moveSingleDisk(char moveFrom, char moveTo);
void calcHanoi(int n);
int main (int argc, const char * argv[])
{
calcHanoi(5);
return 0;
}
void calcHanoi(int n)
{
int count = moveTower(n, 'A', 'B', 'C');
}
int moveTower(int n, char start, char finish, char temp)
{
if (n == 1)
return moveSingleDisk(start, finish);
return
moveTower(n-1, start, temp, finish) +
moveSingleDisk(start, finish) +
moveTower(n-1, temp, finish, start);
}
int moveSingleDisk(char moveFrom, char moveTo)
{
cout << moveFrom << " -> " << moveTo << endl;
return 1;
}