汉诺塔-java

支持韩老师-java学习地址:https://www.bilibili.com/video/BV1fh411y7R8?p=226

汉诺塔-Hanoi.java

代码:

package lbxx.day07.demo01;

public class Hanoi {
     
    public static void main(String[] args){
     
      Tower  t = new Tower();
      t.move(5,'A','B','C');
    }
}
class Tower{
     
    //num 表示要移动的个数, a, b, c 分别表示 A 塔,B 塔, C 塔
    public void move(int num,char a,char b,char c){
     
        if(num == 1){
     
            System.out.println(a + "->" + c);
        }else{
     
            //如果有多个盘,可以看成两个 , 最下面的和上面的所有盘(num-1)
            // (1)先移动上面所有的盘到 b, 借助 c
            move(num-1,a,c,b);
            //(2)把最下面的这个盘,移动到 c
            System.out.println(a + "->" + b);
            //(3)再把 b 塔的所有盘,移动到 c ,借助 a
            move(num-1,a,b,c);
        }
    }
}

运行结果:

D:\Java\jdk-9.0.4\bin\java.exe "-javaagent:D:\JetBrains\IntelliJ IDEA Educational Edition 2021.1.1\lib\idea_rt.jar=52640:D:\JetBrains\IntelliJ IDEA Educational Edition 2021.1.1\bin" -Dfile.encoding=UTF-8 -classpath D:\IdeaProjects\basic-java\out\production\day01 lbxx.day07.demo01.Hanoi
A->C
A->C
A->B
A->B
A->B
A->B
A->C
A->C
A->B
A->B
A->C
A->C
A->C
A->C
A->B
A->B
A->B
A->B
A->C
A->C
A->C
A->C
A->B
A->B
A->C
A->C
A->B
A->B
A->B
A->B
A->C

Process finished with exit code 0

你可能感兴趣的:(JAVA)