zoukankan      html  css  js  c++  java
  • 【牛刀小试1】汉诺塔

    【牛刀小试1】汉诺塔

    主要知识:

    1.        递归

    2.        函数

    3.        If-else

    4.        静态变量

      //汉诺塔

       汉诺塔是一种游戏,有三个塔分别标为A、B、C。A塔上套有n个盘子,

    分别从下往上由大到小排列着。游戏的目的是要把A塔的盘子移到C塔上。

    每次移动之后。都不同意出现大盘子在小盘子上面的情况。

     

    分析:

        我们要把A塔的盘子移到C塔,则必须借助B塔(当n= 1时除外),再移

    到C塔。

        当n= 1时。A->C

             当n= 2时,A->B,A->C,B->C

             当n= 3时,A->C,A->B,C->B,A->C,B->A,B->C,A->C

             当n=....

    解答:採用递归函数(自调用)

    #include <stdio.h>
     
    //tower函数的定义。使用递归(自调用)
    //參数分别为:层数,塔A,塔B,塔C
    void tower( int num, char a, char b, char c)
    {
             staticint count= 0; //静态局部变量,生存周期为整个程序
              
             if(num== 1 )
             {
                       count++;  //count= count+ 1;
                      
                       printf("第%3d步: %c->%c
    ",count, a, c ); //%3d为字宽为3
             }
             else
             {
                       count++;
                       tower(num- 1, a, c, b ); //自己调用自己
            
                 printf( "第%3d步:%c->%c
    ",count, a, c );
            
                 tower( num- 1, b, a, c );
             }
            
             return;
    }
     
     
    int main( void )
    {
             intn;  //n为A塔的层数
            
             printf("输入A的层数: " );
             scanf("%d", &n );
            
             //函数tower的调用 
             tower(n, 'A', 'B', 'C' );
            
             return0;
    }
     

    执行结果:

     

    【指尖的微笑】错误在所难免,希望得到大家的指正^-^

    转载时保留原文的链接http://oursharingclub.joinbbs.nethttp://blog.csdn.net/mirrorsbeyourself

  • 相关阅读:
    pandas中的时间序列基础
    Python中的进程
    Pandas透视表和交叉表
    Pandas分组级运算和转换
    Python中的线程详解
    Pandas聚合
    Python面试题整理
    Pandas分组
    暑假集训 || 动态规划
    DFS || HDU 2181
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5137514.html
Copyright © 2011-2022 走看看