我正在实施河内塔问题以了解更多关于递归的信息。我能够使用 3 peg 案例来实现它,但是,当我想使用更多 pegs(以产生更少的移动)时,我理解 Frame-Stewart 解决方案,我必须打破我拥有的磁盘数量并堆叠到一个peg上当我将磁盘从源钉转移到带有所有中间钉的目标钉时,切勿触摸该钉。但是,我不明白如何将 move(disks, 1, i, {2...K}) 之类的东西写成函数。当我从一开始都不知道它们时,如何在函数原型中写出所有钉子的名称?我在下面给出了我为 3 磁盘解决方案所做的工作,但我需要有关更一般情况的帮助。
// private member function: primitive/basic move of the top disk
// from the source peg to the destination peg -- and legality-check
void move_top_disk(int source, int dest)
{
cout << "Move disk " << towers[source].front() << " from Peg ";
cout << source+1 << " to Peg " << dest+1;
towers[dest].push_front(towers[source].front());
towers[source].pop_front();
if (true == is_everything_legal())
cout << " (Legal)" << endl;
else
cout << " (Illegal)" << endl;
}
// private member function: recursive solution to the 3 Peg Tower of Hanoi
void move(int number_of_disks, int source, int dest, int intermediate)
{
if (1 == number_of_disks)
{
moves++;
move_top_disk (source, dest);
}
else
{
moves++;
move (number_of_disks-1, source, intermediate, dest);
move_top_disk (source, dest);
move (number_of_disks-1, intermediate, dest, source);
}
}
我不明白我需要对我的“移动”功能做出什么样的改变来解决一个 6 钉的情况。谢谢