河内之塔

来源:互联网 发布:大话数据库 好不好 编辑:程序博客网 时间:2024/04/30 01:58

#include <stdio.h>#include <stdlib.h>void hanio(int n,char A,char B,char C){    if(n==1){        printf("Move sheet %d from %c to %c\n",n,A,C);    }    else{        hanio(n-1,A,C,B);        //利用递归,将A上n-1个盘子,先挪到位子B上        printf("Move sheet %d from %c to %c\n",n,A,C);        //上面的n-1个盘子已经都放到位子B上,所以第n个盘子,直接挪到位子C上        hanio(n-1,B,A,C);        //但现在上面的n-1个盘子还都在位子B上,需要把它们放到位子C上    }}int main(){    int n;    printf("Enter the number of the sheet: ");    scanf("%d",&n);    hanio(n,'A','B','C');    return 0;}

原创粉丝点击