public class TowerOfHanoi {
public static void main(String[] args) {
System.out.print("Enter number of disks: ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
TowerOfHanoi toh = new TowerOfHanoi();
System.out.println("The move are:");
toh.moveDisks(n, 'A', 'B', 'C');
}
private void moveDisks(int n, char fromTower, char toTower, char auxTower) {
if(n == 1) {
System.out.println("Move disks " + n + " from " + fromTower + " to " + toTower);
}
else {
moveDisks(n - 1, fromTower, auxTower, toTower); // 借助塔 B 将前 n - 1 个盘子从 A 移到 C
System.out.println("Move disks " + n + " from " + fromTower + " to " + toTower); //将盘子 n 从 A 移到 B
moveDisks(n - 1, auxTower, toTower, fromTower); //借助塔 A 将 n - 1 个盘子从 C 移到 B
}
}
}
转载于:https://my.oschina.net/are1OfBlog/blog/181857