思路是:
要将:n层汉诺塔从柱子1移动至柱子3
则需:把柱子1从上往下数(n-1)层汉诺塔从柱子1移动到柱子2,将最后一层移动到柱子3,将柱子2的(n-1)层汉诺塔移动到柱子3。
规定函数move(int n,int begin,int end),即将柱子begin从上往下数n层汉诺塔,将它们移动至柱子end,递归调用move函数,实现汉诺塔的移动。
package p;
public class Main {
public static int step;
public static int findRest(int a,int b){
return 6-a-b;
}
public static void move(int n,int begin,int end){ //move函数将柱子begin从上往下数n层汉诺塔,将它们移动至柱子end.
int rest = findRest(begin,end);
if(n==1){
System.out.println(begin+"->"+end);
step++;
}
else{
move(n-1,begin,rest);
move(1,begin,end);
move(n-1,rest,end);
}
}
public static void main(String[] args) {
step=0;
move(5,1,3); //将5层汉诺塔从柱子1移动至柱子3.
System.out.println(step+" steps in total.");
}
}