汉诺塔的递归实现
想把1、2、3全部从a移动到c,就肯定先把1、2移动到b! 然后把3移动到c!
问题就变成了吧1、2 从b移动到c,那么a就变成了工具杆子!
代码实现:
public static void hanoi2(int n) {
if (n > 0) {
func(n, "left", "right", "mid");
}
}
public static void func(int N, String from, String to, String other) {
if (N == 1) { // base
System.out.println("Move 1 from " + from + " to " + to);
} else {
func(N - 1, from, other, to);
System.out.println("Move " + N + " from " + from + " to " + to);
func(N - 1, other, to, from);
}
}