1. 程式人生 > 實用技巧 >4.八數碼 BFS

4.八數碼 BFS

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 //用雜湊表來存所有距離
 4 int bfs(string start) {
 5     string end = "12345678x"; //終止狀態
 6     queue<string> q; //寬搜的佇列
 7     unordered_map<string, int> d; //寬搜的陣列
 8     q.push(start);
 9     d[start] = 0; //起點到起點的距離是零
10     int dx[4] = {-1, 0
, 1, 0}, dy[4] = {0, 1, 0, -1}; 11 while (q.size()) { 12 string t = q.front(); 13 q.pop(); 14 if (t == end) { 15 return d[t]; 16 } 17 int distance = d[t]; 18 //狀態轉移 19 int k = t.find('x'); //找到x的位置 20 int x = k / 3, y = k % 3; //找到在3 * 3方格中的位置
21 for (int i = 0; i < 4; i++) { 22 int a = x + dx[i], b = y + dy[i]; 23 if (a >= 0 && a < 3 && b >= 0 && b < 3) { 24 swap(t[k], t[3 * a + b]); //狀態更新 25 if (d.count(t) == 0) { //如果更新完之後的狀態t沒有被搜到的話 26 q.push(t); //
就找到了一個新的狀態 27 d[t] = distance + 1; //更新新的狀態的距離 28 } 29 swap(t[k], t[3 * a + b]); //恢復狀態 30 } 31 } 32 } 33 return -1; 34 } 35 int main() { 36 string start = ""; //初始狀態 37 for (int i = 0; i < 9; i++) { 38 string c; 39 cin >> c; 40 start += c; 41 } 42 cout << bfs(start) << endl; 43 return 0; 44 }

手寫雜湊表的方法之後補上