我正在做一本书的练习,要求我们使用递归方法解决河内塔问题。我已经找到了一个解决方案,但是从我浏览互联网后收集的信息来看,我的解决方案可能不正确。有谁知道解决问题的更好/不同的方法?有没有人有改进的建议。(顺便说一句,输出是正确的。它只应该告诉从哪个塔到另一个钉子正在移动,而不是具体是哪个钉子)
这是代码:
#include <iostream>
#include <cmath>
using namespace std;
static int counter = 0;
void ToH(int dskToMv, int cLocation, int tmpLocation, int fLocation)
{
if (dskToMv == 0);
else
{
if (dskToMv%2!=0)
{
cout << cLocation << "->" << tmpLocation << endl;
cout << cLocation << "->" << fLocation << endl;
cout << tmpLocation << "->" << fLocation << endl;
ToH(dskToMv-1, cLocation, fLocation, tmpLocation);
}
else if (dskToMv%2==0)
{
counter++;
if (counter%2==0)
cout << fLocation << "->" << cLocation << endl;
else
cout << cLocation << "->" << fLocation << endl;
ToH(dskToMv-1, tmpLocation, cLocation, fLocation);
}
}
}
int main()
{
int x, j;
cout << "Enter number of disks: ";
cin >> x;
j = pow(2.0, x-1)-1;
if (x%2==0)
ToH(j, 1, 2, 3);
else
ToH(j, 1, 3, 2);
return 0;
}
这种方法是否符合递归条件?