编程语言
首页 > 编程语言> > 递归算法-汉诺塔

递归算法-汉诺塔

作者:互联网

class HanoiTower{
    public static void main(String[] array){
        Tower tower=new Tower();
        tower.towerMove(3, 'A', 'B', 'C');  
        }
}
//num是盘的数量。a,b,c是三个塔。
class Tower{
    public  void towerMove(int num,char a,char b,char c){
        if(num==1){
            System.out.println(a+" move to "+c);
        }else{//如果有多个盘,可以看成两个盘,最下面的和上面的所有盘(num-1)
            towerMove(num-1,a,c,b);//移动上面的所有盘子到b,借助c盘
            System.out.println(a+ " move to "+c);
            towerMove(num-1,b,a,c);
        }c
    }
}

执行结果如下
/*
A move to C
A move to B
C move to B
A move to C
B move to A
B move to C
A move to C
 */

  

标签:递归,move,towerMove,char,算法,num,汉诺塔,Tower,out
来源: https://www.cnblogs.com/HappyBeibei/p/16574362.html