递归解决 汉诺塔
class Han{
int num;
int steps;
Han(int num){
this.num=num;
}
void total()
{
System.out.println("total="+steps);
}
void show(int i, int from, int des, String[] str)
{
int tmp = 3-from-des;//0+1+2=3
if (i==2)
{
System.out.println(1+":"+str[from]+"->"+str[tmp]);
System.out.println(2+":"+str[from]+"->"+str[des]);
System.out.println(1+":"+str[tmp]+"->"+str[des]);
steps+=3;
}else
{
show(i-1, from, tmp, str);
System.out.println(i+":"+str[from]+"->"+str[des]);
show(i-1, tmp, des, str);
steps+=1;
}
}
} public class HelloWorld{
public static void main(String[] args) {
Han h=new Han(5);//set numbers of member
String[] str= {"A","B","C"};//three pillars
h.show(h.num, 0, 2, str);//from pillar 0 to pillar 2
h.total();//2^n-1
}
}