100行C代码实现字符打印汉诺塔

#include 

/*-------------------------------------------\
| 仅供于实现功能,看情况自己再添加延时函数等实现动画效果 |
\-------------------------------------------*/

/*定义每个柱子的数据结构-->数组*/
int zhuzi_a[]={0,0,0,0,0,0,0,0,0,0};
int zhuzi_b[]={0,0,0,0,0,0,0,0,0,0};
int zhuzi_c[]={0,0,0,0,0,0,0,0,0,0};
/*定义数组指针*/
int *p_a = zhuzi_a;
int *p_b = zhuzi_b;
int *p_c = zhuzi_c;

/*从柱子上取出最上面的一个盘子*/
int zhuzi_pop(int *zhuzi)
{
    int i,pop;
    for(i=0;i<=9;i++)
    {
        if(zhuzi[i] != 0)/*从前往后比较,遇到不为0的元素,将其取出,并将该位置置0 */
        {
            pop = zhuzi[i];
            zhuzi[i] = 0;
            return pop;/*返回取到的元素*/
        }
    }
}
/*放进一个盘子到柱子上*/
void zhuzi_push(int *zhuzi,int push)
{
    int i;
    for(i=0;i<=9;i++)
    {
        if(zhuzi[i] != 0)/*从前往后比较,遇到不为0的元素,将拿到的push放到前一个位置上 */
        {
            zhuzi[i-1] = push;
            return;
        }
        else if(i == 9)/*柱子是空的,放到最底下一个位置*/
        {
            zhuzi[9] = push;
            return;
        }
    }
}
/*画画函数-->打印三个柱子的盘子状况 */
void zhuzi_huahua()
{
    int i,j,a,b,c;
    for(i=0;i<=9;i++)
    {
        for(j=0;j<=112;j++)
        {
            /*获取每一层三个柱子的盘子情况  */

            a = 2*zhuzi_a[i]-1;
            b = 2*zhuzi_b[i]-1;
            c = 2*zhuzi_c[i]-1;
            /*打印*/
            if(j>=(19-a)&j<=(17+a)|j>=(57-b)&j<=(55+b)|j>=(95-c)&j<=(93+c))
            {
                printf("+");
            }
            else if(j == 18|j ==56|j==94)
            {
                printf(" ");
            }
            else if(j==37|j==75)
            {
                printf("#");
            }
            else
            {
                printf(" ");
            }
        }
        printf("\n");
    }
    printf("-----------------------------------------------------------------------------------------------------------------\n");
}

/*移动盘子的函数 */
void move(int *start,int *end)
{
    int i;
    zhuzi_push(end,zhuzi_pop(start));/*将盘子移动到目标柱子 */
    zhuzi_huahua();
}
/*递归算法函数*/
void hanoi(int n,int *from,int *denpend_on,int *to)
{
    if (n==1)
    move(from,to);
    else
    {
      hanoi(n-1,from,to,denpend_on);
      move(from,to);
      hanoi(n-1,denpend_on,from,to);
    }
}

/*主函数*/
int main()
{
    int n,i;
    printf("Please enter the number of dishes:\n");
    scanf("%d",&n);
    while(n>10)
    {
        printf("Plates must be less than or equal to 10!\n");
        scanf("%d",&n);
    }
    for(i=1;i<=n;i++)
        zhuzi_a[9-n+i] = i;/*给柱子A赋值,从大到小依次放入底部,zhuzi_a[9]是底  */
    printf("start...:\n");
    hanoi(n,p_a,p_b,p_c);
    return 0;
}

你可能感兴趣的:(100行C代码实现字符打印汉诺塔)