所以我想计算调用函数 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
我试图追踪问题,但递归使得追踪这类事情变得非常困难(至少对我而言)。
任何帮助或解释将不胜感激!谢谢 :)