我正在执行河内塔问题,以了解更多关于递归的知识。我能够使用3 peg的情况来实现它,但是,当我想要使用更多的钉子(为了产生更少的移动)时,我理解了框架-Stewart解决方案,在这个解决方案中,我必须打破我拥有的磁盘数量,并将其叠加到一个peg上,并且在我将磁盘从源挂钩转移到具有所有中间连接的目标挂钩时,不要碰那个挂钩。但是,我不明白如何编写像move(磁盘,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种固定的情况。谢谢
发布于 2012-09-21 03:02:42
您将需要修改最后一个代码块,其中它确实移动,移动顶磁盘,移动.
这是一篇关于河内塔N根桩的解决方案的文章:Towers of Hanoi with K pegs
https://stackoverflow.com/questions/12523259
复制相似问题