io流2

                                                   递归

      昨天描述了io流的一系列操作,今天来讲一讲递归,前面我们写了很多算法,有很多都可以递归实现,递归简化了代码,比如说n的阶乘,是一种很很好用的编程技巧,

递归典型问题: 梵塔问题(汉诺塔问题)
已知有三根针分别用A, B, C表示,在A中从上到下依次放n个从小到大的盘子,现要求把所有的盘子
从A针全部移到B针,移动规则是:可以使用C临时存放盘子,每次只能移动一块盘子,而且每根针上
不能出现大盘压小盘,找出移动次数最小的方案.
/*Name:HANOITOWER
*Description:solvethehanoitowerproblembyrecursion
*/
#include<stdio.h>
#include<stdlib.h>
/*movenplates:from-->to,
*thebuffercanbeusedifneeded*/
inthanoi(intn,charfrom,charbuffer,charto)
{
    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;
}

 

递归分为两种,一种是直接递归,一种是间接递归,个人觉着递归并不是所有情况下都可以用,好使就用。

转载于:https://www.cnblogs.com/jingyukeng/p/8927675.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值