io style 2

                                                   recursion

      Yesterday I described a series of operations on the io stream. Today I will talk about recursion. We wrote a lot of algorithms earlier, many of which can be implemented recursively. Recursion simplifies the code, such as the factorial of n, which is very useful. programming skills,

Recursive typical problem: Vatican problem (Tower of Hanoi problem)
It is known that there are three needles represented by A, B, and C respectively. In A, place n plates from small to large in order from top to bottom. Now it is required to put all the plates
Move all the needles from A to B. The movement rule is: C can be used to temporarily store the plate, only one plate can be moved at a time, and each needle is on the
There cannot be a large market over a small one, and find the solution with the smallest number of moves.
/*Name:HANOITOWER
*Description:solvethehanoitowerproblembyrecursion
*/
#include<stdio.h>
#include<stdlib.h>
/*movenplates:from-->to,
*thebuffercanbeusedifneeded*/
inthanoi (intn, charfrom, charbuffer, charter)
{
    if(n==1)
    {
        /*movetheNO.1platedirectly:from-->to*/
        printf("Moveplate#%dfrom%cto%c\n",n,from,to);
        /*theNO.1plateismovedsoreturn*/
        return0;
    }
    else
    {
        /*nplatestobemoved:from-->to,
        *movethen-1platesabove:from-->buffer,
        *givethistasktothenextrecursion*/
        hanoi(n-1,from,to,buffer);
        /*then-1platesaboveweremovedtobuffer,
        *sotheNO.nplatecanbemoveddirectly*/
        printf("Moveplate#%dfrom%cto%c\n",n,from,to);
        /*howeverthen-1platesarestillinbuffer,
        *movethemtotheterminalposition,
        *(the"from"positionhasnoplate,&canbeoneso-calledbuffer)*/
        hanoi(n-1,buffer,from,to);
        /*thetaskgivenisdonesoreturn*/
        return0;
    }
}
intmain()
{
#defineN4
    /*NplatesinA,let'smovethemtoC*/
    hanoi(N,'A','B','C');
    return0;
}

 

There are two types of recursion, one is direct recursion and the other is indirect recursion. Personally, I don’t think recursion can be used in all situations.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324779031&siteId=291194637