Personally think Hanoi this recursive algorithm than the electronic mouse of a few, but once understood also can be, in fact, there are many online code, can be directly referenced. I remember doing Hanoi at the beginning of my freshman day, but the code was long and long and did not understand the result of recursion. Now think of it. Hanoi's algorithm is 3 steps: First, the n-1 on A is moved through C to B. Second, move the bottom plate on a to C. Third, because n-1 all on the B, so the B as a repeat the above step is good. So the algorithm looks much simpler. However, the process of thinking is still very painful and difficult to understand. The benefits of saving data in recursion are also reflected here, and it's amazing.
The Hanoi code is as follows:
#include<stdio.h>voidmove(intn,chara,charb,char c){ if(n==1) printf("\t%c->%c\n",a,c); //当n只有1个的时候直接从a移动到c else { move(n-1,a,c,b); //第n-1个要从a通过c移动到b printf("\t%c->%c\n",a,c); move(n-1,b,a,c); //n-1个移动过来之后b变开始盘,b通过a移动到c,这边很难理解 }} main(){ intn; printf("请输入要移动的块数:"); scanf("%d",&n); move(n,‘a‘,‘b‘,‘c‘);} |
The initial algorithm of C language (Hanoi--recursive algorithm)