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); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)