好的,以下是Java实现汉诺塔的代码:

public class HanoiTower {

    public static void main(String[] args) {
        int n = 3; // 汉诺塔的层数
        char a = 'A'; // 起始柱子
        char b = 'B'; // 中间柱子
        char c = 'C'; // 目标柱子

        hanoi(n, a, b, c);
    }

    public static void hanoi(int n, char a, char b, char c) {
        if (n == 1) {
            System.out.println("将第1个盘子从" + a + "移到" + c);
        } else {
            hanoi(n-1, a, c, b);
            System.out.println("将第" + n + "个盘子从" + a + "移到" + c);
            hanoi(n-1, b, a, c);
        }
    }

}

运行结果:

将第1个盘子从A移到C
将第2个盘子从A移到B
将第1个盘子从C移到B
将第3个盘子从A移到C
将第1个盘子从B移到A
将第2个盘子从B移到C
将第1个盘子从A移到C
用Java写一个汉诺塔的程序吧

原文地址: https://www.cveoy.top/t/topic/JWZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录