刚写的:
package mooonsoft.j2se;
public class Hannoi
{
public Hannoi()
{
}
public static void main(String args[])
{
//set plates number
int plates=2;
//set the zhuzhi
String A="A", B="B", C="C";
System.out.println("the plates number is "+plates);
System.out.println("Hannoi 's method path is ");
hannio(plates, A,B, C);
//print hannoi 's step
System.out.println(" Total steps is "+totalSteps);
}
public static void hannio(int plates, String A, String B, String C)
{
if(plates==1)
{
System.out.println("Step:"+A+"-->"+C);
totalSteps++;
}
else if(plates>1)
{
hannio(plates-1, A, C, B);
System.out.println("Step:"+A+"-->"+C);
hannio(plates-1,B, A, C);
totalSteps++;
}
}
private static int totalSteps=0;
}
注意递归的三个要素:
1)写一个不符合递归的条件
2)递归主体的限制条件,什么条件下调用自身
3)递归主体
缺一不可!
递归比较经典的程序,菲波那契数列,阶层,汉诺塔

博客展示了用Java实现汉诺塔问题的代码,设置了盘子数量和柱子标识,通过递归方法输出汉诺塔移动步骤和总步数。同时强调递归需具备不符合递归的条件、递归主体限制条件及递归主体这三个要素,还提及斐波那契数列等经典递归程序。
542

被折叠的 条评论
为什么被折叠?



