資源描述:
《漢諾塔問題的求解程序》由會員上傳分享,免費在線閱讀,更多相關內(nèi)容在教育資源-天天文庫。
1、1.基于漢諾塔問題的求解程序,分別使用全局變量和局部變量來計算當塔中有n個盤子時需要進行多少步的盤子移動次數(shù)(例如當塔中有5個盤子時,需要移動31次)。提示:當使用局部變量時,函數(shù)的原型可以為longhanoi(int,char,char,char),該函數(shù)的功能是完成hanoi塔的移動并返回其執(zhí)行步數(shù)。方法一:使用局部靜態(tài)變量#includelonghanoi(intn,charone,chartwo,charthree)/*該函數(shù)計算移動盤的步驟并返回移動步數(shù)*/{staticlongintcount=0;/*定義靜態(tài)局部變量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函數(shù)的返回值*/printf("pleaseinputthenumberofdiskes:");scanf("%d",&m);printf("thestepsar
3、efollowing:");steps=hanoi(m,'A','B','C');printf("Theyneed%ldstepstomove",steps);}方法二:使用一般局部變量#includelonghanoi(intn,charone,chartwo,charthree)/*該函數(shù)計算移動盤的步驟并返回移動步數(shù)*/{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函數(shù)的返回值*/printf("pleaseinputthenumberofdiskes:");scanf("%d",&m);printf("thestepsarefollowing:");steps=hanoi(m,'A','B','C');printf("Theyneed%ldste
5、pstomove",steps);}方法三:使用全局變量#includelongcount=0;/*定義全局變量來統(tǒng)計移動步數(shù)*/voidhanoi(intn,charone,chartwo,charthree)/*該函數(shù)計算移動盤的步驟*/{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);}