/*Hanoi Tower 盘子有编号、步次有编号、且含总次数统计的C程序*/
#include<stdio.h>
int i=0;
void movedisc(unsigned n,char fromneedle,char toneedle,char usingneedle)
{
if(n>0)
{
movedisc(n-1,fromneedle,usingneedle,toneedle);
/*函数调用自己:传递实参 n-1个盘,出发fromneedle,目的usingneedle,借用toneedle,_后两者交换了位置 */
++i;
switch(fromneedle) /* 出发针有3种情况:a,b,c */
{
case 'a': switch(toneedle) /*目的针有两种情况:b,c */
{
case 'b': printf("\t[%d]:\t%2d=====>%2d\n",i,n,n); /* [i]:n====>n */
break;
case 'c': printf("\t[%d]:\t%2d=============>%2d\n",i,n,n);
break;
}
break;
case 'b': switch(toneedle) /*目的针有两种情况:a,c */
{
case 'a': printf("\t[%d]:\t%2d<=====%2d \n",i,n,n);
break;
case 'c': printf("\t[%d]:\t %2d=====>%2d\n",i,n,n);
break;
}
break;
case 'c': switch(toneedle) /*目的针有两种情况:a,b */
{
case 'a': printf("\t[%d]:\t%2d<=============%2d\n",i,n,n);
break;
case 'b': printf("\t[%d]:\t %2d<=====%2d\n",i,n,n);
break;
}
break;
}
movedisc(n-1,usingneedle,toneedle,fromneedle);
/*函数调用自己:实参 N-1个盘,出发usingneedle,目的toneedle,借用fromneedle _针位再次交换 */
}
}
void main()
{
unsigned n;
printf("请输入盘子总数:");
scanf("%d",&n); /*键入盘子总数*/
printf("\tneedle:\ta\t b\t c\n"); /*屏上显示列表格式针名 needle: a b c */
movedisc(n,'a','c','b'); /*函数调用:传递实参 n个盘,出发a针,目的c针,借用b针*/
printf("\t Total: %d\n",i); /*屏显列表格式:Total: i({zh1}累计的步号)此行在{zh1}面。 */
}
////////////////////////////////////////////////////////////////////////
当n=6,运行后将命令行截图,并用“画图”打开它,进行“反色”处理,得到:
点击此图可放大