Java中如何解决汉诺塔问题

汉诺塔问题

public class homework {
    static int count=0;
    public static void main(String[] args) {
        int n = 3;
        char [] towers={'A','B','C'};
        hannuotower(n,towers[0],towers[1],towers[2]);
    }
    //将编号为diskNumber的盘子由sourceTower移动到destTower
   public static void move(int diskNumber,
   char sourceTower,char destTower){
        count++;
       System.out.println("移动次数为"+count+"编号为"+
diskNumber+"的盘子从"+sourceTower+"移动到"+destTower);
}
//实现汉诺塔游戏
    public static void hannuotower(int ndisks,char towerA,
    char towerB,char towerC){
        if(ndisks==1){
            //将唯一的盘子从A->C
            move(1,towerA,towerC);
        }else{
            //n>=2
            //先将n-1个盘子从A->B,C作为辅助
            hannuotower(ndisks-1,towerA,towerC,towerB);
            //将编号为n从A->C
            move(ndisks,towerA,towerC);
            //将之前的n-1个盘子从B->C,A作为辅助
            hannuotower(ndisks-1,towerB,towerA,towerC);
        }
    }
}

运行结果为:
在这里插入图片描述

原文链接:加载失败,请重新获取