首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >河内塔-n peg求解算法

河内塔-n peg求解算法
EN

Stack Overflow用户
提问于 2012-09-21 01:51:29
回答 1查看 8K关注 0票数 1

我正在执行河内塔问题,以了解更多关于递归的知识。我能够使用3 peg的情况来实现它,但是,当我想要使用更多的钉子(为了产生更少的移动)时,我理解了框架-Stewart解决方案,在这个解决方案中,我必须打破我拥有的磁盘数量,并将其叠加到一个peg上,并且在我将磁盘从源挂钩转移到具有所有中间连接的目标挂钩时,不要碰那个挂钩。但是,我不明白如何编写像move(磁盘,1,i,{2.K})这样的函数。当我从一开始就不知道的时候,怎么才能写出函数原型中所有连接的名称呢?下面我已经给出了我为3磁盘解决方案所做的工作,但我需要更一般的帮助。

代码语言:javascript
复制
// 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种固定的情况。谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-21 03:02:42

您将需要修改最后一个代码块,其中它确实移动,移动顶磁盘,移动.

这是一篇关于河内塔N根桩的解决方案的文章:Towers of Hanoi with K pegs

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12523259

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档