Java 汉诺塔程序

店铺:https://shop58616120.taobao.com

public class JLang {

public static void main(String[] args){
        JLang t = new JLang();
        t.hanoi(3,'A','B','C');
    }

/**
     * 汉诺塔迭代算法:
     *     1. 以C为中介,将 1 ~ N-1 从 A -> B
     *     2. 以A为中介,将 1 ~ N-1 从 B -> C
     * @param num 塔层数
     * @param a 原始塔层
     * @param b 空
     * @param c 目标塔
     */
public void hanoi(int num,char a,char b,char c){
        if(num == 0) return;
        this.hanoi(num-1,a,c,b);
        System.out.println("move plate p" + num + " from " + a + " to " + c);
        this.hanoi(num-1,b,a,c);
    }
}

评论

© Saoirse | Powered by LOFTER