You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

27 lines
1.1 KiB

1 year ago
import java.util.Scanner;
public class hanoi {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个数n");
int numDisks= scanner.nextInt();
char source = 'A'; // 源柱子
char auxiliary = 'B'; // 辅助柱子
char target = 'C'; // 目标柱子
solveHanoi(numDisks, source, auxiliary, target);
}
public static void solveHanoi(int numDisks, char source, char auxiliary, char target) {
if (numDisks == 1) {
System.out.println("移动盘子 1 从柱子 " + source + " 到柱子 " + target);
} else {
// 将numDisks-1个盘子从源柱子移动到辅助柱子借助目标柱子
solveHanoi(numDisks - 1, source, target, auxiliary);
// 移动最底下的一个盘子到目标柱子
System.out.println("移动盘子 " + numDisks + " 从柱子 " + source + " 到柱子 " + target);
// 将numDisks-1个盘子从辅助柱子移动到目标柱子借助源柱子
solveHanoi(numDisks - 1, auxiliary, source, target);
}
}
}