public class Hanoita{
public static void main(String[]args){
Test t = new Test();
int n = 4;
t.move(n,'A','B','C');
int res = t.step(n) ;
System.out.println("当有" + n + "个盘子时移动的次数为 " + res);
}
}
//A柱上一共n个卡片 ,通过B,移动到C,一次只能一个,小的只能移动到大的上
//三个柱子A,B,C互换
//把柱子上的分成两部分 n , n-1
//先把卡片移动从A借助C到B,再借助A从B移动到C
/*1.方法返回值 void
2.方法名 move
3.形参 (int n ,char front,char middle,char behind)
4.方法体 互换
*/
class Test {
public void move(int n ,char front,char middle,char behind){
//如果只有一个盘的时候,就是从A移动到C
if (n == 1 ){
System.out.println("把1号盘子从" + front + "移动到" + behind);
}
//如果有多个盘子,则分成两部分 ,先从A 借助 C 移动到B
else{
move(n-1,front,behind,middle);
System.out.println("把"+ n + "号盘子从" + front + "移动到" + behind);
//把最下面的盘子从B 借助 A 移动到 C
move(n-1,middle,front,behind);
}
}
//移动的步骤 2 *前面移动的步数 + 1
/* 1个盘 1次
2个盘 2次
3个盘 7次
4个盘 15次
5个盘 31次 */
public int step(int n ){
int s;
if(n == 1){
return 1;
}
else {
s = 2 * step(n-1) + 1;//次数
return s ;
}
}
}
(内存分析图)
递归方法:找到递归的出口,然后一层层的往上返回输出。