河内塔错误

时间:2014-03-20 19:33:38

标签: java recursion methods

好吧,所以我为“河内之塔”活动设计了一个代码。它非常适合递归运动。问题是,当我在输出结果后通过铅笔和纸张解决拼图时,结果证明是错误的。 当n = 2时,拼图工作得很漂亮。但我只是试了n = 3,有些东西不合适。 我的程序旨在使3 peg成为所有作品的最终位置。所以磁盘都在第3页上完成。

public class TowersOfHanoi {

    public static String hanoi(int nDisks, int fromPole, int toPole) 
    {
        int helpPole;
        String Pol1, Pol2, MyStep, MyPol; //contains moves

        if(nDisks ==1)
        {
            return "There is " + nDisks + " disk moving from " + fromPole + "==>" + toPole + "\n";
        }
        else
        {
            helpPole = 6 - fromPole - toPole; //fromPole + helpPole + toPole = 6

            Pol1 = hanoi(nDisks-1, fromPole, helpPole);

            MyStep = "There are/is " + (nDisks-1) + " disk(s) moving from " + fromPole + "==>" + toPole + "\n";

            Pol2 = hanoi(nDisks-1, helpPole, toPole);

            MyPol = Pol1 + MyStep + Pol2; //+ = String concatenation

            return MyPol;

         }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        int n = 3;
        String StepsToSolution;

        StepsToSolution = hanoi (n, 1, 3);

        System.out.println(StepsToSolution);

    }
}

输出:

There is 1 disk moving from 1==>3
There are/is 1 disk(s) moving from 1==>2
There is 1 disk moving from 3==>2
There are/is 2 disk(s) moving from 1==>3
There is 1 disk moving from 2==>1
There are/is 1 disk(s) moving from 2==>3
There is 1 disk moving from 1==>3

1 个答案:

答案 0 :(得分:0)

nDisks告诉方法要移动多少个磁盘。它不是在特定时间移动的标识或磁盘数,而是在某个特定位置其余的作业

因此。总会有一个磁盘从一个挂钩移动到另一个挂钩,而不是2.你在myStep中(nDisks-1)进行1。或者更简单地说,myStep可能是:myStep = hanoi(1, fromPole, toPole);

除此之外,你的动作输出是正确的。这意味着您可以增加更多磁盘并期望正确移动。

相关问题