public class Hanoitower {
//私有计数变量
static int count = 0;
public static void main(String[] args) {
//测试汉诺塔
hanoiTower(3, 'A', 'B', 'C');
System.out.println("步数: " + count);
}
public static void hanoiTower(int num, char a, char b, char c) {
count++;
if (num == 1) {
System.out.println(a + "->" + c);
} else {
//最好自己画一个俩层塔的实例借助树来理解
hanoiTower(num - 1, a, c, b);
System.out.println(a + "->" + c);
hanoiTower(num-1,b,a,c);
}
}
}
Java数据结构 | 递归算法 -- 汉诺塔的代码实现
最新推荐文章于 2022-05-08 08:27:25 发布