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 */
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/279830.html