1

所以我想计算调用函数 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

我试图追踪问题,但递归使得追踪这类事情变得非常困难(至少对我而言)。

任何帮助或解释将不胜感激!谢谢 :)

4

3 回答 3

3

如果您只需要 count 调用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;
}
于 2012-02-17T00:05:11.960 回答
2

您是count按值传递的,因此递归调用moveTower不会修改它的本地副本。通过引用传递:

void moveTower(int n, char start, char finish, char temp, int & count)
                                                              ^

在 内部增加计数器可能会稍微整洁一些moveSingleDisk,而不是在每次调用它之前增加它,因此您可以确保不会错过任何调用。在这种情况下,您也需要通过引用传递。

于 2012-02-16T23:36:58.017 回答
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;
}
于 2012-02-17T00:03:52.677 回答