河内塔[编辑] - k peg解决方案

时间:2012-09-22 15:45:14

标签: c++ data-structures recursion binary-tree towers-of-hanoi

我能够提出一个算法(逻辑)来解决河内塔问题的k-peg解决方案,但是当我实现我的代码时,我得到了分段错误。

void move(int number_of_disks, int source, int dest, vector <int> free_peg, int pointer)
    {
        int p;

        if (1 == number_of_disks)
        {
            moves++;
            move_top_disk (source, dest);
        }

        if(free_peg.size() > 2)
            p = number_of_disks/2;
        else 
            p = number_of_disks - 1;

        moves++;
        //Move top "p" disks from peg 1 to peg i
        move(p, source, free_peg.back(),free_peg, pointer); 
        //Move "n - p - 1" disks from peg 1 to another peg 
        move(number_of_disks - p - 1, source, free_peg[pointer--], free_peg, pointer++);
        //Move the "last disk" from the source peg to the destination
        move_top_disk(source, dest);
        //Move "n - p - 1" disks from peg (i - 1) to the final peg
        move(number_of_disks - p - 1, free_peg[pointer--], dest, free_peg, pointer++);
        //Move "p" disks from peg i to the destination
        move(p, free_peg.back(), dest, free_peg, pointer);
    }

这个想法非常简单,我保留了一个免费钉子(或塔)的向量,当我移动整个磁盘时,我会更新它。因此,对于6个钉子和n个磁盘的情况,我有一个源,一个目的地和4个免费钉。想法是移动(n - p)p~n / 2从源到free_peg [3](第四个自由钉)。现在我的向量中只有3个免费挂钩,我使用这3个免费挂钩将(n - p - 1)个磁盘移动到free_peg [2],然后将最后一个磁盘从源移动到目的地。所以现在我有2个自由钉和1个源= 3个自由钉。接下来,我需要使用3个空闲挂钩(包括现在免费的源)将(n - p - 1)个磁盘从挂钩[2]移动到目的地。最后,使用4个空闲挂钩将p盘从free_peg [3]移动到目的地。但是,当我在我的代码中实现它时,我遇到了分段错误,有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

我能够解决k-peg通用解决方案,感谢您的帮助。以下是该算法的用法:

void move(int number_of_disks, int source, int dest, vector <int> free_peg)
    {
        int p, middle, g;

        if (1 == number_of_disks)
        {
            moves++;
            move_top_disk (source, dest);
        }

        else
        {
            moves++;

            if(free_peg.size() >= 2)
                p = number_of_disks/2;
            else
                p = number_of_disks - 1;

            //Move top "p" disks from peg 1 to peg i
            middle = free_peg.back();
            free_peg.pop_back();
            free_peg.push_back(dest);
            move(p, source, middle,free_peg);

            //Move "n - p " disks from peg 1 to another peg
            free_peg.pop_back();
            move(number_of_disks - p, source, dest, free_peg);

                    //Move p from current peg to the final peg
            free_peg.push_back(source);
            move(p, middle, dest, free_peg);
        }
    }