汉诺塔的递归实现算法,将A中的圆盘借助B圆盘完全移动到C圆盘上,
每次只能移动一个圆盘,并且每次移动时大盘不能放在小盘上面
递归函数的伪算法为如下:
if(n == 1)
直接将A柱子上的圆盘从A移动到C
else
先将A柱子上的n-1个圆盘借助C柱子移动到B柱子上
直接将A柱子上的第n个圆盘移动到C柱子上
最后将B柱子上的n-1个圆盘借助A柱子移动到C柱子上
该递归算法的时间复杂度为O(2的n次方),当有n个圆盘时,需要移动圆盘2的n次方-1次
-
public class HanoiTest {
-
-
static int step = 0;
-
-
-
-
public static void main(String[] args) {
-
hanioSort(3, "A", "B", "C");
-
}
-
-
-
-
-
public static void hanioSort(int num ,String a ,String b ,String c){
-
if(num == 1){
-
move(num,a,c);
-
} else{
-
hanioSort(num-1, a, c, b);
-
move(num,a,c);
-
hanioSort(num-1, b, a, c);
-
}
-
}
-
public static void move(int num ,String a,String b){
-
step ++ ;
-
System.out.println("第"+step+"步,盘子"+num+"从"+a+"塔移到"+b+"塔/n");
-
}
-
}
【数据结构与算法】汉诺塔算法——java递归实现
原文:http://blog.csdn.net/goluck98/article/details/42890137