汉诺塔问题的java算法实现

时间:2022-03-25 13:10:00

         最近在当家教,顺便下复习大一的内容,项目可以做,但是基础还是得扎实。

         汉诺塔问题是递归思想优越性的最权威证明啦。

public class TowerOfHanoi {

public static void main(String[] args) {
Scanner inputScanner=new Scanner(System.in);
System.out.println("请输入盘子的个数");
int n=inputScanner.nextInt();
System.out.println("The moves are :");
moveDisk(n,'A','B','C');
}

private static void moveDisk(int n, char fromTower, char toTower, char auxTower) {

if(n==1)
System.out.println("Move disk 1 from "+fromTower+" to "+toTower);
else {
moveDisk(n-1, fromTower, auxTower, toTower);
System.out.println("Move disk "+n+" from "+fromTower+" to "+toTower);
moveDisk(n-1,auxTower , toTower, fromTower);
}

}

}