您的位置:首页 > 其它

非递归 汉诺塔问题 C实现方法

2013-10-08 22:51 281 查看
//帮同学重案组之虎做的
void move(int k,char from,char thru,char to);

int atop,btop,ctop,count=0;
int a[50],b[50],c[50];
void main()
{
int n,i;
printf("输入盘子的个数:\n");
scanf("%d",&n);
printf("--------工作流程--------\n");
for(i=0;i<n;i++){a[i]=i+1;}
atop=n-1;btop=-1;ctop=-1;
move(n,'A','B','C');
printf("------------------------\n");
printf("移动次数:--->  %d  \n",count);
}
void move(int k,char from,char thru,char to)
{
if(k>=1)
{
move(k-1,from,to,thru);
count++;

if(from=='A'&&to=='B')
{printf(">>> %d---(%d) :  %c ===> %c \n",count,a[atop],from,to);
btop++;b[btop]=a[atop];atop--;
}

else if(from=='A'&&to=='C')
{printf(">>> %d---(%d) :  %c ===> %c \n",count,a[atop],from,to);
ctop++;c[ctop]=a[atop];atop--;
}

else if(from=='B'&&to=='A')
{
printf(">>> %d---(%d) :  %c ===> %c \n",count,b[btop],from,to);
atop++;a[atop]=b[btop];btop--;
}

else if(from=='B'&&to=='C')
{
printf(">>> %d---(%d) :  %c ===> %c \n",count,b[btop],from,to);
ctop++;c[ctop]=b[btop];btop--;
}

else if(from=='C'&&to=='A')
{
printf(">>> %d---(%d) :  %c ===> %c \n",count,c[ctop],from,to);
atop++;a[atop]=c[ctop];ctop--;
}

else if(from=='C'&&to=='B')
{
printf(">>> %d---(%d) :  %c ===> %c \n",count,c[ctop],from,to);
btop++;b[btop]=c[ctop];ctop--;
}

move(k-1,thru,from,to);
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: