私は、再帰的な方法を使用してハノイの塔の問題を解決するように求めている本の演習に取り組んでいます。私は解決策にたどり着きましたが、インターネットを閲覧した後に収集したことから、私の解決策は正しくない可能性があるということです。問題を解決するためのより良い/別の方法を知っている人はいますか? そして、改善のための提案はありませんか。(ところで、アウトプットは正しいです。具体的にどのペグではなく、どのタワーから別のペグが動いているかを伝えることだけが想定されています)
コードは次のとおりです。
#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;
}
このメソッドは再帰として認定されていますか?