用C写的汉诺塔(hanoi)程序
来源:优易学  2011-12-10 16:51:42   【优易学:中国教育考试门户网】   资料下载   IT书店
  #include<stdio.h>
  void movedisc(unsigned n,char fromneedle,char toneedle,char usingneedle);
  int i=0;
  void main()
  {
  unsigned n;
  printf("请输入盘子的数量:");
  scanf("%d",&n); /*输入N值*/
  printf("\t柱子:\t a\t b\t c\n");
  movedisc(n,'a','c','b'); /*从A上借助B将N个盘子移动到C上*/
  printf("\t 共计: %d步\n",i);
  }
  void movedisc(unsigned n,char fromneedle,char toneedle,char usingneedle)
  {
  if(n>0)
  {
  movedisc(n-1,fromneedle,usingneedle,toneedle);
  /*从fromneedle上借助toneedle将N-1个盘子移动到usingneedle上*/
  ++i;
  switch(fromneedle) /*将fromneedle 上的一个盘子移到toneedle上*/
  {
  case 'a': switch(toneedle)
  {
  case 'b': 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 'b': switch(toneedle)
  {
  case 'a': printf("\t[%d]:\t%2d<———%2d\n",i,n,n);
  break;
  case 'c': printf("\t[%d]:\t\t%2d———>%2d\n",i,n,n);
  break;
  }
  break;
  case 'c': switch(toneedle)
  {
  case 'a': printf("\t[%d]:\t%2d<———————%2d\n",i,n,n);
  break;
  case 'b': printf("\t[%d]:\t\t%2d<———%2d\n",i,n,n);
  break;
  }
  break;
  }
  movedisc(n-1,usingneedle,toneedle,fromneedle);
  /*从usingneedle上借助fromneedle将N-1个盘子移动到toneedle上*/
  }
  }
  运行后:
  请输入盘子的数量:3
  柱子: a b c
  [1]: 1———————>1
  [2]: 2———> 2
  [3]: 1<———1
  [4]: 3———————>3
  [5]: 1<——— 1
  [6]: 2———>2
  [7]: 1———————> 1
  共计: 7步
  Press any key to continue...

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训