漢諾塔
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 31 Accepted Submission(s) : 10
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
規則(1):每次只能移動1個圓盤;
規則(2):任何時刻都不允許將較大的圓盤壓在較小的圓盤之上;
規則(3):在滿足移動規則(1)和(2)的前提下,可將圓盤移至a,b,c中任一塔座上。
對於給出的n,請輸出最少步驟的整個移動過程。
Input
Output
Sample Input
3
Sample Output
move 1 from A to C move 2 from A to B move 1 from C to B move 3 from A to C move 1 from B to A move 2 from B to C move 1 from A to C
思路分析:本題是簡單的遞推,分清楚怎麼移動,先把n-1個移到B上,在把B上的N-1通過A移到C上,主要輸出時的處理。
代碼:#include <stdio.h> char ch[3]={'A','B','C'}; void move (int n,int a,int b,int c) { if(n>0) { move (n-1,a,c,b); printf("move %d from %c to %c\n",n,ch[a-1],ch[c-1]); move (n-1,b,a,c); } } int main () { int n; while(scanf("%d",&n)!=EOF) { move (n,1,2,3); printf("\n"); } return 0; }