/************************************
名 称:汉诺塔问题
作 者:freewind
版 本:v1.0
时 间:2006-08
Email:freewind22@163.com
*************************************/
#include <stdio.h>
#include <process.h>
#include <conio.h>
#define MAX 10
int PAGE=32;
int X[MAX], Y[MAX], Z[MAX];
int max,maxpage;
long step,maxstep=1;
void Show(int n)
{
int i;
for(i=0;i<n;i++)
{
printf(" │");
if( X[i] ) printf("%-2d",X[i]); else printf(" ");
printf(" │");
if( Y[i] ) printf("%-2d",Y[i]); else printf(" ");
printf(" │");
if( Z[i] ) printf("%-2d",Z[i]); else printf(" ");
printf(" /n");
}
printf(" ┴ ┴ ┴ /n");
}
void move(char s, char d )
{
int *from,*to;
int i,j,page;
switch(s)
{
case 'A':
from=X;
if( d=='B' ) to=Y; else to=Z;
break;
case 'B':
from=Y;
if( d=='A' ) to=X; else to=Z;
break;
case 'C':
from=Z;
if( d=='A' ) to=X; else to=Y;
break;
}
for(i=0;i<max;i++)
if( from[i] ) break;
for(j=max-1;j>=0;j--)
if( !to[j] ) break;
to[j]=from[i];
from[i]=0;
Show( max );
step++;
if(step % PAGE ==0 )
{
page=step/PAGE;
printf(" 共 %d 页,当前为 %d -- %d 步.第 %d 页.按任意键继续.../n",maxpage,(page-1)*PAGE+1,page*PAGE,page);
getch();
}
else if(step>=maxstep)
{
page=step/PAGE+1;
printf(" 共 %d 页,当前为 %d -- %d 步.第 %d 页./n",maxpage,(page-1)*PAGE+1,step,page);
}
}
void hanoi(char a,char b,char c,int count)
{
if( count==1)
{
/*printf("%c --> %c/n",a,c);*/
move(a,c);
}
else
{
hanoi(a,c,b,count-1);
/*printf("%c --> %c/n",a,c);*/
move(a,c);
hanoi(b,a,c,count-1);
}
}
void main()
{
int i,count=3;
char a='A',b='B',c='C';
printf("汉诺塔问题: 请输入圆盘数(1-%d)/n",MAX);
scanf("%d",&count);
if(count<1 || count>MAX )
{
printf("输入错误!/n");
exit(0);
}
for(i=0;i<count;i++)
X[i]=i+1;
if(count==9) PAGE=25;
if(count==10) PAGE=20;
max=count;
maxstep<<=count;
maxstep--;
maxpage=(maxstep-1)/PAGE+1;
/*printf("总步数: %ld 总页数: %d 每页数: %d/n",maxstep,maxpage,PAGE);*/
Show(count);
hanoi(a,b,c,count);
}
本文提供了一个汉诺塔问题的实现方案,通过递归算法演示了如何将不同大小的盘子从一个柱子移动到另一个柱子的过程,并通过C语言程序详细展示了整个解题过程及可视化步骤。
994

被折叠的 条评论
为什么被折叠?



