电竞比分网-中国电竞赛事及体育赛事平台

分享

【C++實現(xiàn)】五大常用算法之一:分治算法(實例:漢諾塔)

 長沙7喜 2018-12-10

求解思想:大而化小

1、問題拆分成子問題

2、對子問題求解

在漢諾塔游戲中,有三個分別命名為A、B、C得塔座,幾個大小各不相同,從小到大一次編號得圓盤,每個原盤中間有一個小孔。最初,所有得圓盤都在A塔座上,其中最大得圓盤在最下面,然后是第二大,以此類推.

先上代碼

  1. #include<iostream>
  2. using namespace std;
  3. class Move
  4. {
  5. public:
  6. void moveGo(int i, int a, int b, int c);
  7. void display(int i, int a, int b);
  8. private:
  9. static int count;
  10. };
  11. int Move::count = 1;
  12. void Move::moveGo(int i, int a, int b, int c)
  13. {
  14. if (1 == i)
  15. {
  16. display(1, a, b);
  17. }
  18. else
  19. {
  20. moveGo(i - 1, a, c, b);
  21. display(i, a, b);
  22. moveGo(i - 1, c, b, a);
  23. }
  24. }
  25. void Move::display(int i, int a, int b)
  26. {
  27. printf("第 %d 步:移動第 %d 個塔從 %d 根柱子到 %d 根柱子\n", count,i, a, b);
  28. count++;
  29. }
  30. int main()
  31. {
  32. Move mo;
  33. mo.moveGo(4,1,2,3);
  34. cout << endl;
  35. system("pause");
  36. return 0;
  37. }

核心代碼

  1. void Move::moveGo(int i, int a, int b, int c)
  2. {
  3. if (1 == i)
  4. {
  5. display(1, a, b);
  6. }
  7. else
  8. {
  9. moveGo(i - 1, a, c, b);
  10. display(i, a, b);
  11. moveGo(i - 1, c, b, a);
  12. }
  13. }

思想:

  1. 如果只有1個塔,那么把這個塔直接從a移動到  display(1, a, b);
  2. 如果有n個塔,把n-1個從a移動到c                    moveGo(i - 1, a, c, b);
  3. 然后把剩下的一個從a移動到b                           display(i, a, b);
  4. 最后把n-1個從c移動到b                                    moveGo(i - 1, c, b, a);

這樣問題就已經(jīng)求解完了

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多