未命名

檔案下載:39238375

  

/** * 漢諾塔問題 * * 精確計算出到底需要移動多少次才能夠將漢諾塔從柱子A搬到柱子B(柱子C作緩沖) * 輸入:漢諾塔的層次數 * 輸出:移動次數和移動動作 * 思路:遞歸 * 使用:直接在main函數new Test(漢諾塔的層次數) * * @author Fiay * */ public class Test { private static String a = "柱子A"; private static String b = "柱子B"; private static String c = "柱子C"; private int level; private int turns; /*省略Getter and Setter*/ public Test(){} public Test(int level){ this.level = level; this.turns = getTurnsByLevel(this.level); System.out.println("完成!\n共需要"+turns+"步"); } public int getTurnsByLevel(int level){ System.out.println("漢諾塔層次數为:"+level+"\n開始!"); showSolution(level,a,b,c); return turns-1; } public void showSolution(int level,String a,String b,String c){ if(level>0){ showSolution(level-1,a,c,b); System.out.println(turns+" - 從("+a+")移到("+b+")\t"); showSolution(level-1,c,b,a); }else{ turns++; } } public static void main(String args[]){ new Test(2); //new Test(3); //new Test(4); } }
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()