The initial algorithm of C language (Hanoi--recursive algorithm)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.