递归之汉诺塔

递归之汉诺塔

源代码

package 递归基础小题;

/**
 * @author 邓雪松 (づ ̄ 3 ̄)づ)
 * @create 2021-10-24-21-02
 */
public class 汉诺塔 {
    public static void main(String[] args) {
        printHonoiTower(3,"A","B","C");
    }

    /**
     *
     * @param N 初始的N个从小到大的盘子,N是最大编号
     * @param from 原始柱子
     * @param to 目标的柱子
     * @param help 辅助柱子
     */
    static void printHonoiTower(int N,String from,String to,String help){
        if(N==1){
            System.out.println("move "+N+" from "+from+" to "+to);
            return;
        }
        printHonoiTower(N-1,from,help,to);//先把前N-1个盘子挪到辅助空间上去
        System.out.println("move "+N+" from "+from+" to "+to);//N可以顺利到达target
        printHonoiTower(N-1,help,to,from);//让N-1从辅助空间回到原空间上去
    }
}

运行结果

move 1 from A to B
move 2 from A to C
move 1 from B to C
move 3 from A to B
move 1 from C to A
move 2 from C to B
move 1 from A to B

如果不明白执行次序可以敲出来然后debug

上一篇:MaC MySQL教程,一行一行代码基础学习


下一篇:【算法】计数排序