河内的塔递归

时间:2016-05-09 18:55:26

标签: java recursion towers-of-hanoi

我一直在努力创建一个程序来解决使用递归思维的河内塔。我在网上看了很多,无法弄清楚为什么代码不断打印错误的东西。以下是我到目前为止的情况:

public static void tower(int start, int finish, int helper, int number)
      {
         if(number == 1)
            System.out.println("Move disk 1 from "+start+" to "+finish+".");
         else
         {
            tower(start, finish, helper, (number - 1));
            System.out.println("Move disk "+number+" from "+start+" to "+finish+".");
            tower(helper, start, finish, (number - 1));
         }      
      }
   }

但它一直打印出来:

Move disk 1 from 1 to 3.
Move disk 2 from 1 to 3.
Move disk 1 from 2 to 1.
Move disk 3 from 1 to 3.
Move disk 1 from 2 to 1.
Move disk 2 from 2 to 1.
Move disk 1 from 3 to 2.

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这应该有效:

a = fun("( (2, 3), (1, 4) )")
print (a)
>>> [(2, 3), (1, 4)]
a[0]
>>> (2, 3)
a[0][1]
>>> 3

public static void tower(int start, int finish, int helper, int number) { if(number == 1) System.out.println("Move disk 1 from "+start+" to "+finish+"."); else { tower( start, helper, finish, number-1); System.out.println("Move disk "+number+" from "+start+" to "+finish+"."); tower( helper, finish, start, number - 1); } } 的输出:

tower(1, 3, 2, nDisks);