打印n层汉诺塔从最左边移动到最右边的全部过程
递归时:from to help三个柱子 n层
base case:当n == 1时,直接从from移动到to上
要想完成将n层的汉诺塔从from移动到to,采用递归时,只需要考虑 n 和 n-1 层之间的关系
步骤1:将n-1层从from移动到help上面
步骤2:将第n层从from移动到to上面
步骤3:将n-1层从help移动到to上面
public class Hanoi {
//移动n层汉诺塔 从最左边移动到最右边
public static void hanoi(int n){
if(n <= 0) return;
move(n, "left", "mid", "right");
}
public static void move(int n, String left, String mid, String right){
if(n == 1){
System.out.println("move from " + left + " to " + right);
return;
}
move(n - 1, left, right, mid);
move(1, left, mid, right);
move(n - 1, mid, left, right);
}
public static void main(String[] args){
hanoi( 4 );
}
}