汉诺塔问题求解

    技术2022-05-19  20

    要求:碟子的个数为n,把它从x通过y全部搬到z中。

     

    思路:若n==1,直接从x搬到z;

             否则,先借助z把n-1个从x搬到y,在把第n个从x中搬到z中,再借助x,把y中n-1个搬到z中

     

    测试代码如下:

    #include<stdio.h>void hanoi(unsigned char  n,char x,char y,char z);int main(){ unsigned int n; char x='x',y='y',z='z'; printf("Please input the number of the disks/n"); scanf("%d",&n); if(n==0) {  printf("Please input a positive number/n");  scanf("%d",&n); } hanoi(n,x,y,z); return 0;} void hanoi(unsigned int  n,char x,char y,char z){ if(n==1)  printf("Move %d from %c  to  %c/n",n,x,z); else {  hanoi(n-1,x,z,y);  printf("Move %d from %c  to  %c/n",n,x,z);  hanoi(n-1,y,x,z); }}

     


    最新回复(0)