浏览 2036 次
锁定老帖子 主题:汉诺塔问题
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-04-29
如下面代码: public class HanoiTest { private static int size = 3; public static void main(String[] args) { Hanoi(size, 'A', 'B', 'C'); } public static void Hanoi(int num, char from, char ch, char to) { if(num == 1) System.out.println("Moving disk 1 from " + from + " to " + to); else { Hanoi(num-1, from, to, ch); System.out.println("Moving disk " + num + " from " + from + " to " + to); Hanoi(num-1, ch, from, to); } } }
输出如下:
Moving disk 1 from A to C Moving disk 2 from A to B Moving disk 1 from C to B Moving disk 3 from A to C Moving disk 1 from B to A Moving disk 2 from B to C Moving disk 1 from A to C
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2009-05-01
汉诺塔也算得上是一道经典的递归题了,不知道楼主有没有尝试过用迭代做?
|
|
返回顶楼 | |