该游戏是在一块铜板装置上,有三根杆(编号A、B、C),在A杆自下而上、由大到小按顺序放置N个金盘。游戏的目标:把A杆上的金盘全部移到C杆上,并仍保持原有顺序叠好。操作规则:每次只能移动一个盘子,并且在移动过程中三根杆上都始终保持大盘在下,小盘在上,操作过程中盘子可以置于A、B、C任一杆上。
我们需要打印这个移动的顺序。
我们将三个杆子分别称为,start,end,other,
完成这个,我们只需要三步
:将N-1层的盘子通过end移动到other上
:将N层的盘子从start移动到end上
:将N-1层的盘子通过start移动到end上去。
在其子过程也是一样的操作。
当到达最顶层的时候也就是只有一个盘子的时候直接移动就行了。
public static void hanoi(int n) {
if(n> 0) {
func(n,"左","右","中");
}
}
public static void func(int i,String start,String end,String other) {
if(i == 1) {
System.out.println("Move 1 from " + start + " to" + end);
}else {
//第一步先将上面i-1个从start移动到other上,借助end
func(i-1,start,other,end);
//第二步将第i个移动到end上
System.out.println("Move"+ i + "from" + start + " to " + end);
//第三步将i-1个从other移动到end上,借助start。
func(i-1,other,end,start);
}
}