漢諾塔的故事(C語言——遞迴)

來源:互聯網
上載者:User

標籤:傳說   har   stdio.h   font   ret   https   move   bsp   tps   

漢諾塔:

  漢諾塔(又稱河內塔)問題是源於印度一個古老傳說的益智玩具。大梵天創造世界的時候做了三根金剛石砫子,在一根柱子上從下往上按照大小順序摞著64片黃金圓盤。大梵天命令婆羅門把圓盤從下面開始按大小順序重新擺放在另一根柱子上。並且規定,在小圓盤上不能放大圓盤,在三根柱子之間一次只能移動一個圓盤。

 

 1 #include <stdio.h> 2 int move(int n, char x, char y, char z){/* 將 n 個圓盤藉助 y 從 x 移動到 z */ 3     if(n == 1){ 4         printf("%c -> %c\n", x, z);/* 當只有一個圓盤的時候,直接移動到z */ 5     }else{ 6         move(n-1, x, z, y);/* 將n-1個圓盤藉助 z 從 x 移動到 y */ 7         printf("%c -> %c\n", x, z);/* 將最後的一個圓盤從 x 移動到 z */ 8         move(n-1, y, x, z);    /* 將 n-1 個圓盤藉助 x 從 y 移動到 z */     9     }10     return 0;11 12 }13 int main(){14     int n;15     printf("請輸入漢諾塔的層數:");16     scanf("%d",&n);17     move(n, ‘X‘, ‘Y‘, ‘Z‘);18 19     return 0;20 }

 

漢諾塔的故事(C語言——遞迴)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.