漢諾塔問題求解

來源:互聯網
上載者:User

標籤:數學建模   演算法   迭代   

                        漢諾塔問題求解

問題描述:A,B,C三個柱子,其中A插著n個盤子從上到下按照小到大放,嘗試以B盤子為中介,每次移一次,將A中的盤子從上到下按照小到大插;


演算法:n個盤子全放在A上面,分為兩步走:將前面(n-1)個盤子全部放到B上面,然後將第n個盤子放到C中;
                                      這樣子B中就有(n-1)個盤子,再以A為中介,全部放到C中。
 數學建模:
      設n個盤子需要放An次,
      An=A(n-1)+1+A(n-1);n=a,An=1;

     通過簡單的迭代,即可求出An=2^n-1;


程式實現:
    hanoi(n,A,B,C)
      =Move(A,C)  if(n=1)
       hanoi(n-1,A,C,B);
       Move(A,C)
       hanoi(n-1,B,A,C)
       
       

 #include "stdafx.h"#include "iostream" using namespace std; void  move(char A,char B) { //char A,B; printf("%c-------%c\n",A,B); }    void hanoi(int n,char A,char B,char C)  { // int n; //char A,B,C;  if(n==1)  move(A,C);  else  {  hanoi(n-1,A,C,B);  move(A,C);  hanoi(n-1,B,A,C);  }  }    int main()  {  int n;  cin>>n; // char A,B,C;  hanoi(n,'A','B','C');   while(1);  return 0;  }
     運行代碼如下:







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.