思路:“把大象放进冰箱共需要3步,把长颈鹿放进冰箱共需要4步。 答案解释:把大象放进冰箱共需要3步。第一步:打开冰箱门;第二步:把大象装进去;第三步:关好冰箱门。把长颈鹿放进冰箱共需要4步。第一步:打开冰箱门;第二步:把大象取出来;第三步:把长颈鹿装进去;第四步:关好冰箱门。
Java代码如下:
package com.company;
public class Hanoi {
public static void main(String[] args) {
hanoi(3);
}
public static void hanoi(int n){
if (n>0){
fun(n,"左","右","中");
}
}
private static void fun(int n, String from, String end, String other) {
if (n==1){ //base case
System.out.println("Move 1 from" + from + "to" + end );
}else {
fun(n-1,from,other,end);
System.out.println("Move "+ n + "from" + from + "to" +end);
fun(n-1,other,end,from);
}
}
}