java利用递归解决汉诺塔问题

180 阅读1分钟
public class test_Hanoi {
    public static void main(String[] args) {
        hanoi(3, 'A', 'B', 'C');
    }
    /*
    n        共有n个盘子
    from     开始的柱子
    in       中间的柱子
    to       目标柱子
    无论有多少个盘子,都认为是只有两个盘子:最上面的一个盘子和下面的所有盘子
    * */

    public static void hanoi(int n, char from, char in, char to) {
        //只有一个
        if (n == 1) {
            System.out.println("从第1个盘子: " + from + " 移到 " + to);
        } else {
            //移动上面所有的盘子到中间位置
            hanoi(n-1, from, to, in);
            //移动下面的盘子,
            System.out.println("从第" + n + "个盘子: " + from + " 移到 " + to);
            //把上面的所有盘子从中间位置移到目标位置
            hanoi(n-1,in,from,to);

        }
    }
}

以3为例子输出:
在这里插入图片描述