用C写的汉诺塔(hanoi)程序

    技术2022-05-11  24

    #include<stdio.h>

    void movedisc(unsigned n,char fromneedle,char toneedle,char usingneedle);

    int i=0;

    void main(){unsigned n;printf("请输入盘子的数量:");scanf("%d",&n); /*输入N值*/printf("/t柱子:/t a/t b/t c/n");movedisc(n,'a','c','b'); /*从A上借助B将N个盘子移动到C上*/printf("/t 共计: %d步/n",i);}

    void movedisc(unsigned n,char fromneedle,char toneedle,char usingneedle){if(n>0){   movedisc(n-1,fromneedle,usingneedle,toneedle);   /*从fromneedle上借助toneedle将N-1个盘子移动到usingneedle上*/   ++i;   switch(fromneedle) /*将fromneedle 上的一个盘子移到toneedle上*/   {    case 'a': switch(toneedle)    {     case 'b': printf("/t[%d]:/t-———>-/n",i,n,n);     break;     case 'c': printf("/t[%d]:/t-———————>-/n",i,n,n);     break;    }    break;    case 'b': switch(toneedle)    {     case 'a': printf("/t[%d]:/t-<———-/n",i,n,n);     break;     case 'c': printf("/t[%d]:/t/t-———>-/n",i,n,n);     break;    }    break;    case 'c': switch(toneedle)    {     case 'a': printf("/t[%d]:/t-<———————-/n",i,n,n);     break;     case 'b': printf("/t[%d]:/t/t-<———-/n",i,n,n);     break;    }    break;   }   movedisc(n-1,usingneedle,toneedle,fromneedle);

       /*从usingneedle上借助fromneedle将N-1个盘子移动到toneedle上*/}}

     

    运行后:

    请输入盘子的数量:3        柱子:    a           b           c        [1]:     1———————>1        [2]:     2———> 2        [3]:                  1<———1        [4]:     3———————>3        [5]:     1<——— 1        [6]:                  2———>2        [7]:     1———————> 1         共计: 7步Press any key to continue...


    最新回复(0)