public class Hanoi {
public static void move(int n, char from, char to) {
System.out.println("Disk " + n + " from " + from + " to " + to);
}
public static void hanoi(int n, char from, char inter, char to) {
if(n == 1) {
move(1, from, to);
}else {
// n-1 disks from --> to --> inter
hanoi(n-1, from, to, inter);
move(n, from, to);
// n-1 disks inter --> from --> to
hanoi(n-1, inter, from, to);
}
}
public static void main(String[] args) {
hanoi(3, 'a', 'b', 'c');
}
}
汉诺塔 Java
最新推荐文章于 2024-05-15 18:36:04 发布