用递归方法写出3阶汉诺塔的操作

littlev19 2006-03-23 11:35:53
用递归方法写出3阶汉诺塔的操作
...全文
150 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wizardblue 2006-03-24
  • 打赏
  • 举报
回复
/**
* The Tower of Hanoi (sometimes referred to as the Tower of Brahma or the End
* of the World Puzzle) was invented by the French mathematician, Edouard Lucas,
* in 1883. He was inspired by a legend that tells of a Hindu temple where the
* pyramid puzzle might have been used for the mental discipline of young
* priests. Legend says that at the beginning of time the priests in the temple
* were given a stack of 64 gold disks, each one a little smaller than the one
* beneath it. Their assignment was to transfer the 64 disks from one of the
* three poles to another, with one important provisoøa large disk could never
* be placed on top of a smaller one. The priests worked very efficiently, day
* and night. When they finished their work, the myth said, the temple would
* crumble into dust and the world would vanish.
*
* @author protozz
*
*/
public class TowerOfHanoi {

public void move(int disks, char a, char b, char c) {
if (disks > 0) {
move(disks - 1, a, c, b);
System.out.println("Move " + a + " to " + c);
move(disks - 1, b, a, c);
}
}
public static void main(String[] args) {
TowerOfHanoi t = new TowerOfHanoi();
t.move(3,'a','b','c');
}
}
Sanco 2006-03-24
  • 打赏
  • 举报
回复
简单的一个,手写的,没编译,测试。

public class Hanoi
{
public static void main(String[] args)
{
action(3, 'A', 'B', 'C');
}

//把n个盘子从a移到c,通过b
public static void action(int n, char a, char b, char c)
{
if (1 == n)
{
System.out.println("move Dish No.:" + n + " from " + a + " to " + c);
} else
{
action(n-1, a, c, b);
System.out.println("move Dish No.:" + n + " from " + a + " to " + c);
action(n-1, b, a, c);
}
}
}

也没考虑堆栈溢出。
不过希望有人把这个用迭代算法实现的思想或者代码(带注释)贴出来看看。
见笑了。
ztroma 2006-03-23
  • 打赏
  • 举报
回复
多少阶都可以做,当然,要考虑堆栈溢出的情况~移动次数是2^n-1

62,629

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧