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

//帮同学重案组之虎做的
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);
  }
}

转载于:https://my.oschina.net/arunu/blog/167316

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值