C语言hanoi问题

Python011

C语言hanoi问题,第1张

程序有点问题,帮你改了:

#include

<stdio.h>

void

main()

{

void

hanoi(int

n,char

one,char

two,char

three)

int

m

printf("请输入碟子数:")

scanf("%d",&m)

printf("执行步骤:\n")

hanoi(m,'A','B','C')

}

void

hanoi(int

n,char

one,char

two,char

three)

{

void

move(char

x,char

y)

if(n==1)

move(one,three)

else

//加花括号

{

//整个过程是一个递归的过程,一直到递归出口再往回返

hanoi(n-1,one,three,two)//把上面的n-1个盘子,借助第3根柱子,移动到第2根柱子上

move(one,three)//把最下面的一个盘子移动到最终的目标柱子上

hanoi(n-1,two,one,three)//接下来把前面移动第2根柱子上的n-1个盘子中的n-2个盘子,借助第1根柱子,移动到第3根柱子上

}

}

void

move(char

x,char

y)

{

printf("%c-->%c\n",x,y)

}

//测试结果:

Hanoi问题是一个递归问题。

要将A柱n个盘的移动C柱,则之前必须将A柱的前n-1个盘移动到B柱。

明白这一点再加上C的递归特性,解决的思路就很简单。

要只显示第一步,只要在n==2的时候加个小小的判断即可,第一次进去的就是第一步,以后的不打印就好了。

hanoi(from ,to ,help ,n)

{

if (n==1)

{

printf("move NO1 $from to $to )

return

}

else if (n==2)

{

printf("move No2 from $from to $help")

printf("move No1 from $from to $to")

printf("move No2 from $help to $to")

}

else

{

hanoi(from,help,to, number-1)

printf("move $number from $from to $to")

}

}