汉诺塔小例子

闲来无事,做个汉诺塔试试机器性能

警告:请谨慎设置盘子的数目,机器性能不好的非常容易卡死

    public static void main(String... args) {
        Instant start = Instant.now();
        moveTower(3, 'A', 'B', 'C');
        Instant end = Instant.now();
        Duration time = Duration.between(start, end);
        long seconds = time.getSeconds();//秒表示
        long millis = time.toMillis();//毫秒表示
        System.out.println(seconds);
        System.out.println(millis);
    }

    /**
     * N个盘子从A经过B移动到C
     * 标记盘子从小到大 1——>n号
     *
     * @param n 盘子的数目
     * @param A 源座
     * @param B 辅助座
     * @param C 目的座
     */
    public static void moveTower(int n, char A, char B, char C) {
        //如果只有1个盘子,直接从A移动到C
        if (n == 1) {
            System.out.println("盘1从" + A + "移动到" + C);
        } else {
            //否则上面n-1个盘子通过C移动到B柱子上
            moveTower(n - 1, A, C, B);
            //然后把第n个盘子直接从A移到C柱上
            System.out.println("盘" + n + "从" + A + "移动到" + C);
            //再把其余移到B上的盘子通过A移动到C上,就完成了
            moveTower(n - 1, B, A, C);
            //通过递归,传入的n会逐渐减少,ABC对应的位置也会不断变化,最终化解为移动一个盘子
        }
    }

你可能感兴趣的:(汉诺塔小例子)