读书人

递归: 汉诺塔( 急 ! 栈)解决办法

发布时间: 2012-02-13 17:20:26 作者: rapoo

递归: 汉诺塔( 急 ! 栈)
void hanoi(int n,char one,char two,char three) // 定义hanoi函数
// 将n个盘从one座借助two座,移到three座
{
void move(char x,char y); // 对move函数的声明
if(n==1)
move(one,three);
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}

递归 hanoi(n-1,one,three,two);/这里有个问题,当hanoi(等于1时)不是直接输出了吗?
他怎么会执行?
move(one,1,three);
hanoi(1,two,one,three);



[解决办法]
void hanoi(int n,char one,char two,char three){
if(n == 1){
System.out.println("move " + n + "from " + one + "to " + three);
}
else
{
hanoi(n-1,one,three,two);
System.out.println("move " + n + "from " + one + "to " + three);
hanoi(n-1,two,one,three);
}
}
[解决办法]
“递归 hanoi(n-1,one,three,two);/这里有个问题,当hanoi(等于1时)不是直接输出了吗?”

LZ这里你要多理解一下了,下面是我以前回复别人帖子的完整分析过程:

以3层为例:

hannuo(3,a,b,c)
{
hannuo(2,a,c,b)
{
hannuo(1,a,b,c)
A--C
move(a,b)
A--B
hannuo(1,c,a,b)
C--B
}
move(a,c)
A--C
hannuo(2,b,a,c)
{
hannuo(1,b,c,a)
B--A
move(b,c)
B--C
hannuo(1,a,b,c)
A--C
}
}

读书人网 >软件架构设计

热点推荐