汉诺塔问题, 图形分页显示每一步.

/************************************
名 称:汉诺塔问题
作 者: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);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值