1. 程式人生 > >2007百度之星總決賽試題八方塊移動的簡單演算法

2007百度之星總決賽試題八方塊移動的簡單演算法

八方塊移動遊戲要求從一個含8個數字(用1-8表示)的方塊以及一個空格方塊(用0表示)的3x3矩陣的起始狀態開始,
不斷移動該空格方塊以使其和相鄰的方塊互換,直至達到所定義的目標狀態。
空格方塊在中間位置時有上、下、左、右4個方向可移動,在四個角落上有2個方向可移動,在其它位置上有3個方向可移動。
例如,假設一個3x3矩陣的初始狀態為:

  8   0   3  
  2   1   4  
  7   6   5  

  要求的目標狀態為:  
  1   2   3  
  8   0   4  
  7   6   5  

  則一個合法的移動路徑為:  
  8   0   3           8   1   3          8   1   3          0   1   3         1   0   3         1   2   3  
  2   1   4   =>   2   0   4   =>   0   2   4   =>   8   2   4   => 8   2   4   => 8   0   4  
  7   6   5           7   6   5          7   6   5          7   6   5          7   6   5        7   6   5  

另外,在所用可能的從初始狀態到目標狀態的移動路徑中,步數最少的路徑被稱為最短路徑;
在上面的例子中,最短路徑為5。如果不存在從初始狀態到目標狀態的任何路徑,則稱該組狀態無解。   
 請設計演算法找到從八方塊的某初始狀態到某目標狀態的所有可能路徑的最短路徑

  1. #define WIN32_LEAN_AND_MEAN     
  2. #define _CRT_SECURE_NO_DEPRECATE
  3. #include <iostream>
  4. #include <map>
  5. #include <queue>
  6. #include <cstring>
  7. #include <ctime>
  8. #include <cassert>
  9. const unsigned int strLength = 9;
  10. usingnamespace std;
  11. // 交換字串src中 x和y的值,返回被交換後的新串
  12. char* swap(char* src, int x, int y)
  13. {
  14.     assert(strlen(src)==strLength);
  15. char* dest = newchar[strLength+1];
  16.     strcpy(dest, src);
  17. char temp = dest[x];
  18.     dest[x] = dest[y];
  19.     dest[y] = temp;
  20. return dest;
  21. }
  22. //為Map<char*,char*>提供的比較函式.用於比較字串值,取代預設的比較字串地址
  23. struct ltstr
  24. {
  25. bool operator()(constchar* s1, constchar* s2) const
  26.     {
  27. return strcmp(s1, s2) < 0;
  28.     }
  29. };
  30. //核心演算法,start為初始狀態 goal為目標狀態
  31. //沒有使用A* 演算法 或啟發式尋找 我在這個題目中,我找不到這樣的啟發條件. 
  32. //我覺的啟發式並不一定能得到最優解 這題明確要求是最短路徑
  33. //用隊來實現廣度優先 用map來儲存所有節點.實現圖的效果 map中每項資料由<節點,節點的父節點>構成
  34. //返回值為兩種狀態需要的最短步數.
  35. int FindStep(char* start, char* goal)
  36. {
  37.     assert(strlen(start)==strLength);
  38.     assert(strlen(goal)==strLength);
  39.     map<char*, char*, ltstr> strMap;
  40.     map<char*, char*,ltstr>::iterator iter;
  41.     queue<char*> strQueue;
  42.     strQueue.push(start);
  43.     unsigned int step = 0;
  44. while (!strQueue.empty())
  45.     {
  46. char* str = strQueue.front();
  47.         strQueue.pop();
  48. //確定節點中字元'0'所在的位置
  49.         unsigned int pos;
  50. for (pos = 0; pos < strLength && str[pos] != '0'; pos++);
  51. //由當前結點移位得到4個新的子結點的指標陣列初始為NULL
  52. char* generate[4];
  53. for (int i = 0; i < 4; i++)
  54.             generate[i] = NULL;
  55. //當前節點左移 右移 上移 下移 並生成新節點 
  56. if ((pos % 3) != 0) generate[0] = swap(str, pos, pos - 1);
  57. if ((pos % 3) != 2) generate[1] = swap(str, pos, pos + 1);
  58. if (pos > 2)        generate[2] = swap(str, pos, pos - 3);
  59. if (pos < 6)        generate[3] = swap(str, pos, pos + 3);
  60. //處理生成的四個新節點
  61. for (int i = 0; i < 4; i++)
  62.         {
  63. if (generate[i] == NULL)
  64. continue;
  65. //如果此結點圖中(Map中)已存在,刪除此結點 並返回
  66. if (strMap.find(generate[i]) != strMap.end())
  67.             {
  68. delete generate[i];
  69. continue;
  70.             }
  71. //如果此結點不是目標狀態節點則入隊,並將此節點加入圖中
  72. if (strcmp(generate[i], goal) != 0)
  73.             {
  74.                 strQueue.push(generate[i]);
  75.                 strMap.insert(make_pair(generate[i], str));
  76. continue;
  77.             }
  78.             strMap.insert(make_pair(generate[i], str));
  79. char *back = generate[i];
  80. //執行到這裡則說明此結點為目標狀態結點遁環查詢其父結點
  81. while (strcmp(back, start) != 0)
  82.             {
  83.                 step++;
  84.                 back = (strMap.find(back))->second;
  85.                 cout << back << "/n";
  86.             }
  87. //釋放記憶體 並返回步數;
  88. for (iter = strMap.begin(); iter != strMap.end(); iter++)
  89. delete iter->first;
  90. return step;
  91.         }
  92.     }
  93. //目標狀態不可到達 釋放記憶體 返回-1;
  94. for (iter = strMap.begin(); iter != strMap.end(); iter++)
  95. delete iter->first;     
  96. return -1;
  97. }
  98. int main()
  99. {
  100. //char* start = "803214765";
  101. char* start = "784356102";
  102. char* goal = "123804765";
  103. //char* goal = "012345678";
  104.     cout << "開始尋找..." << endl;
  105. clock_t  startTime = clock();
  106.     cout << "需要 " << FindStep(start, goal) << " 步.(如果為-1則目標狀態不可到達) /n";
  107.     cout << "共用時" << (clock() - startTime) << "毫秒.(關閉FindStep函式中的cout輸出可以更快點) "<<endl;
  108.     system("PAUSE");
  109. return 0;
  110. }