Java hanoiTower

markdown #說明 經典的河內塔遊戲,主要是遞迴的觀念,需要想一下, #操作流程 ##Code ``` import java.io.*; class HanoiTowerGame{ void go (int discs) { hanoiTower('A','C','B',discs); } //move void moveDisc(char source ,char target, int disc) { System.out.println("move "+ disc + " from " + source +" to "+ target); } //a:source //b:empty //c:target //discs: number of disk void hanoiTower(char a ,char c,char b, int discs) { if (discs ==1 ) {// if number of disk is 1 //just move it to target moveDisc(a,c,discs); return; } //move disks to B exception the biggest disk hanoiTower(a,b,c,discs-1); //move the biggest to c moveDisc(a,c,discs); //move disk in B to C hanoiTower(b,c,a,discs-1); } } public class hanoi { public static void main(String [] argv)throws IOException { HanoiTowerGame game=new HanoiTowerGame(); BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); System.out.print("please input the nuber of disks"); int discs= java.lang.Integer.parseInt(br.readLine()); game.go(discs); } } ``` ##Demo
- code

留言