资源描述:
《汉诺塔问题的求解程序》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、1.基于汉诺塔问题的求解程序,分别使用全局变量和局部变量来计算当塔中有n个盘子时需要进行多少步的盘子移动次数(例如当塔中有5个盘子时,需要移动31次)。提示:当使用局部变量时,函数的原型可以为longhanoi(int,char,char,char),该函数的功能是完成hanoi塔的移动并返回其执行步数。方法一:使用局部静态变量#includelonghanoi(intn,charone,chartwo,charthree)/*该函数计算移动盘的步骤并返回移动步数*/{staticlongintcount=0;/*定义静态局部变量count,用以计算总共移动他多少次*/i
2、f(n==1){printf("move%c-->%c",one,three);count++;}else{hanoi(n-1,one,three,two);printf("move%c-->%c",one,three);count++;hanoi(n-1,two,one,three);}return(count);}voidmain(){intm=0;longintsteps;/*定义长整型变量step用来装载hanoi函数的返回值*/printf("pleaseinputthenumberofdiskes:");scanf("%d",&m);printf("thestepsar
3、efollowing:");steps=hanoi(m,'A','B','C');printf("Theyneed%ldstepstomove",steps);}方法二:使用一般局部变量#includelonghanoi(intn,charone,chartwo,charthree)/*该函数计算移动盘的步骤并返回移动步数*/{longintcount1=0,count2=0;/*定义局部变量count1,count2*/if(n==1)printf("move%c-->%c",one,three);else{count1=hanoi(n-1,one,thre
4、e,two);printf("move%c-->%c",one,three);count2=hanoi(n-1,two,one,three);}return(count1+count2+1);}voidmain(){intm=0;longintsteps;/*定义长整型变量step用来装载hanoi函数的返回值*/printf("pleaseinputthenumberofdiskes:");scanf("%d",&m);printf("thestepsarefollowing:");steps=hanoi(m,'A','B','C');printf("Theyneed%ldste
5、pstomove",steps);}方法三:使用全局变量#includelongcount=0;/*定义全局变量来统计移动步数*/voidhanoi(intn,charone,chartwo,charthree)/*该函数计算移动盘的步骤*/{if(n==1){printf("move%c-->%c",one,three);count++;}else{hanoi(n-1,one,three,two);printf("move%c-->%c",one,three);count++;hanoi(n-1,two,one,three);}}voidmain(){int
6、m=0;printf("pleaseinputthenumberofdiskes:");scanf("%d",&m);printf("themovingstepsarefollowing:");hanoi(m,'A','B','C');printf("Theyneed%ldstepstomove",count);}