hanoi(n,x,y,z)
{
hanoi(n-1,x,z,y);//n-1 from x to y
move(x,z);//x->z
hanoi(n-1,y,x,z);//n-1 from y to z
}
hanoi(n-1,x,z,y)
{
hanoi(n-2,x,y,z);//n-2 from x to z
move(x,y);//n-1 from x to y
hanoi(n-2,z,x,y);//n-2 from z to y
}
the step move(x,y) is what you must do to realize hanoi(n-2,x,y,z),at last ,the last step will meet the first step that you can implement easily,this is the deepest I can comprehend
//11072013 add
对hanoi T的印象从大二接触C语言开始
其实算法非常简单,当盘子的个数为n时,移动的次数应等于2^n – 1(有兴趣的可以自己证明试试看)。后来一位美国学者发现一种出人//摘自百度
#include <stdio.h>
#define N 2 //N disks on original pillar void hanoi(char src, char mid, char dst, int n)
{
if (n == 1)
{
printf("Move disk %d from %c to %c\n", n, src, dst);
}
else {
hanoi(src, dst, mid, n - 1);
printf("Move disk %d from %c to %c\n", n, src, dst);
hanoi(mid, src, dst, n - 1);
}
} int main(void)
{
hanoi('A', 'B', 'C', N);
return 0;
}
借鉴了其他人的思路,总算稍微理解了上述算法的实现,整理步骤要点
the fact is that wo don't konw how to do but konw wo must do,and push to opration to the stack memory until we move the topest disk to Z
a)step befor moving n to Z,the case is 1 to n-1 are on Y,the mothed is move n to Z,push the opration//the last opration
b)the last second situation is 1 to n-2 are on X,the mothed is move n-1 to Z,push the opration//second last opration
d)it is ease to see the first step is move n-(n-1) to X or Y
a and b is what we must do,and we have no other choices,but what has hanppend bettwen b and c,the stack has store all the oprations wo must do until c
assume the function can move 1 to n-1 to X or Y, so it can move 1 to n-2 to X or Y,and so on n-(n-1) to X or Y,it is easy to move n-(n-1) to X or Y
the reverse order you or the functon you build may implement,
e)n-1 disks on Y,put n on Z//after that,you can omit n on Z
f)n-2 disks on X,n-1 on Y//put the n-1 on Z,the question return to a,so a and b is the whole task need to resolve
****the last situation is 2 disks on X or Y
the whole steps is like ,if 1 OK,then 2OK;if 2 OK,then 3 OK
个人感悟:1,有时候踢皮球也是一种办法,此处是往上踢,有点默认路由的味道,没有别的选择
2,当你身处多级环境中,而且视野范围有限的情况下,只能虚构方法,即使不知道方法是怎么实现
3,the original case only permit taking one disk once,but it does't conflact with the step e and f,e and f is the situation we need implement but the mothed we use.The mothed is very simple,anyone can see directly,we image the situation first ,here the mothed is not the point
4,let the stack store the opration but not your head
5,用递归证明可以实现,用反证证明只有一种方式