思路:
主要思路:
三个柱子:原柱子、.中间柱(辅助)、目标柱
汉诺塔主要分为3个步骤:
1、A借助C,把n-1个移动到B;
2、A把第n个移动到C;
3、B借助A,把n-1个移动到C。
程序:
import java.util.Scanner;
public class Hanoi {
static int count = 0;//移动的次数
public static void hanoi(int n, char a, char b, char c) {
if(n == 1) {
System.out.println("n = " + n + ", " + a + "-->" + c);
}else {
//1、A借助C,把n-1个移动到B
hanoi(n-1, a, c, b);
//2、A把第n个移动到C
System.out.println("n = " + n + ", " + a + "-->" + c);
//3、B借助A,把n-1个移动到C
hanoi(n-1, b, a, c);
}
count ++;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println("移动方案为:");
hanoi(num, 'A', 'B', 'C');
System.out.println("移动次数为:" + count);
}
}