汉诺塔算法(经典递归算法)

import java.util.Scanner;

/**
 * @Author: machi
 * @Date:2019/2/17
 */
public class TowerOfHanoi {


    static long count;//移动的次数

    static void hanoi(int n, char a, char b, char c) {//汉诺塔算法
        if (n == 1) {
            System.out.printf("第%d次移动:\t圆盘从%c棒移动到%c棒\n", ++count, a, c);
            
        } else {
            hanoi(n - 1, a, c, b);//递归调用
            System.out.printf("第%d次移动:\t圆盘从%c棒移动到%c棒\n", ++count, a, c);

            hanoi(n - 1, b, a, c);//递归调用

        }

    }

    public static void main(String[] args) {
        System.out.println("汉诺塔算法问题求解");
        count = 0;
        Scanner input = new Scanner(System.in);
        System.out.print("请输入汉诺塔圆盘的数量:");
        int n = input.nextInt();
        hanoi(n, 'A', 'B', 'C');
        System.out.printf("总共需要%d步移动", count);

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42470710/article/details/87522354