“汉诺塔问题”的Java重写思路:典型的递归问题。
“汉诺塔问题”的Java重写代码:
public class Hanoi {
public static final String A = "第一根柱子";
public static final String B = "第二根柱子";
public static final String C = "第三根柱子";
public static void main(String[] args) {
System.out.println("Hello Mr.Zuo!");//向左老师致敬
int numOfDisks = 5;
System.out.println("圆盘数量为:"+ numOfDisks);
System.out.println("开始移动");
moveHanoi(numOfDisks,A,B,C);
System.out.println("移动完成");
}
private static void moveHanoi(int n,String a,String b,String c){
if(n == 1){
logMove(1,a,c);
}else{
moveHanoi(n-1,a,c,b);
logMove(n,a,c);
moveHanoi(n-1,b,a,c);
}
}
private static void logMove(int n,String x,String y){
System.out.println("把第" + n + "个圆盘从" + x +"移动到" + y + "上");
}
}
“汉诺塔问题”的Java重写运行结果: