C++ 河内塔-n-peg求解算法

C++ 河内塔-n-peg求解算法,c++,recursion,recursive-datastructures,towers-of-hanoi,C++,Recursion,Recursive Datastructures,Towers Of Hanoi,我正在实现河内塔问题,以了解更多关于递归的知识。然而,当我想使用更多的钉(以产生更少的移动)时,我能够使用3钉案例实现它我理解Frame Stewart解决方案,在将磁盘从源销钉转移到目标销钉(使用所有中间销钉)的过程中,我必须打破现有磁盘的数量并将其堆叠到一个销钉上,并且永远不要触摸该销钉。但是,我不明白如何将move(disks,1,I,{2…K})之类的东西作为函数编写。当我从一开始就不知道函数原型中所有peg的名字时,我怎么能写出它们的名字呢?我已经在下面给出了我为3磁盘解决方案所做的工

我正在实现河内塔问题,以了解更多关于递归的知识。然而,当我想使用更多的钉(以产生更少的移动)时,我能够使用3钉案例实现它我理解Frame Stewart解决方案,在将磁盘从源销钉转移到目标销钉(使用所有中间销钉)的过程中,我必须打破现有磁盘的数量并将其堆叠到一个销钉上,并且永远不要触摸该销钉。但是,我不明白如何将move(disks,1,I,{2…K})之类的东西作为函数编写。当我从一开始就不知道函数原型中所有peg的名字时,我怎么能写出它们的名字呢?我已经在下面给出了我为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);
        }
    }
//私有成员函数:顶部磁盘的基本/基本移动
//从源peg到目标peg——以及合法性检查
无效移动\u顶部\u磁盘(int源,int目标)
{

cout您将需要修改最后一块代码,它会移动到哪里,移动顶部磁盘,移动


这是一篇关于解决N桩河内塔问题的文章:

你至少应该告诉大家你的“麻烦”是什么,我不知道如何实现移动功能。我不知道如何包含两个以上用于中间切换的塔。因此在我的移动功能中,我必须做一些类似于移动的事情(#disk,source,inter1,inter2,inter3,inter4,dest)?是的。但是,我认为,为任何自定义N实现它是有意义的(因此,如果您决定有8个peg,您不必修改所有例程)。但是我如何写move(#disk,source,N=1到N=4,dest)在声明函数之前不知道n的值吗?我不需要知道声明像void foo(int,int)这样的函数需要什么吗…如何为将要传递的参数动态添加int?如果在编写代码时不知道参数的数量,请使用类似数组的方法传递参数。这是命令行参数的工作方式。