汉罗塔问题

class hanluota {
    public static void main(String[] args) {
        int nDisks = 2;
        move(nDisks, 'A', 'B', 'C');
    }

    public static void move(int n, char from, char other, char to) {
        if (n == 1) {
            System.out.println("Disk 1 from " + from + " to " + to);
            return;
        }
        move(n - 1, from, to, other); //  此时to,也传送进去了,但是没有被使用,用到的变量一直是 from 和 to ,other 只是辅助空间
        System.out.println("Disk " + n + " from " + from + " to " + to);
        move(n - 1, other, from, to);
    }

    // 我们知不知道高阶汉罗塔怎么移动,不知道,但是我们从最少的汉罗塔的移动中找到了他的规律,利用计算机的性能,运算出了它的答案
    // 具体的编码中,
    // 1. base case ,
    // 2. 每个子递归中需要完成的步骤,如果你不知道如何如何写出这个递归,你的思路是,先写一个例子,1层,再写一个例子,2层,最后一直写到多层
    // 3. 使用多个变量,然后复用这几个变量,一般有计数器n ,然后有额外变量 ,容器other,
    // 4. 我们有了大流程,移动上面的n-1 层,在移动n 层,知道 n-1层移回正确位置,这个数据规模一直在减少,每个子递归都完成一个流程设计
}
posted @ 2021-06-22 15:21  庭有奇树  阅读(78)  评论(0编辑  收藏  举报