汉诺塔(Hanoi)经典递归问题

Paste_Image.png

package com.Hanoi.cn;
import java.util.Scanner;
public class Hanoi {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Hanoi1(n,'A','B','C');
        
    }
    
    private static void move(int n,char from ,char to){
        System.out.println("第" + (++Global.i) + "步:   " + "把第" + n + "个从" + from + "----->" + to );
        //把字符在塔之间进行移动打印出来
    }
    
    private static void Hanoi1(int n,char from,char mid,char to){
        if(n==1){
            move(1,from,to);      //从第一个塔移动到第三个塔,from第一,to第三
        }
        if(n>1){
            Hanoi1(n-1,from,to,mid);     //当个数变多了形成规律的三个步骤进行
            move(n,from,to);
            Hanoi1(n-1, mid, from, to);
        }
    }
}
package com.Hanoi.cn;
public class Global {
    public static int i=0;
}

推荐阅读更多精彩内容