汉诺塔问题:三个塔left,middle,right,n个盘子从小到大依次叠放在left塔上,现每次只能移动一个盘子,并且只能将小盘放在大盘上,求最优步骤使得n个盘子从left移动到right,借助middle。
分析:由题意可列出三个递推式:
1、当n=1时,直接一步left to right;
2、1~n-1盘子从left移到middle,借助right;
3、此时left只有第n个盘子,直接移到right;
4、此时left塔为空,将middle的n-1个盘子借助left移到right
所以可以得到递推式,其中递推变量为n-1
public class Hannuota{
void move(int n,String left,String right){
System.out.println(String.format("第%d编号盘子从%s移动到%s",n,left,right);
}
void hannuota(int n,String left,String middle,String right){
if(n==1) move(n,left,right);
else{
hannuota(n-1,left,right,middle);//1~n-1 frome left to the middle,use right
move(n,left,right);//the n number frome left to the right
hannuota(n-1,middle,left,right);//last,1~n-1 frome middle to the right,use left
}
}
public static void main(String[] args){
//设起始塔为left,借助塔为middle,目标塔为right
int n = 6;
new Hannuota().hannuota(n,"left","middle","right");
}
}