九宫重排
描寫敘述
如以下第一個圖的九宮格中,放著 1~8 的數字卡片,另一個格子空著。與空格子相鄰的格子中的卡片能夠移動到空格中。經過若干次移動。能夠形成第二個圖所看到的的局面。我們把第一個圖的局面記為:12345678.把第二個圖的局面記為:123.46758顯然是按從上到下。從左到右的順序記錄數字,空格記為句點。本題目的任務是已知九宮的初態和終態,求最少經過多少步的移動能夠到達。假設不管多少步都無法到達,則輸出-1。
?
輸入
輸入第一行包括九宮的初態,第二行包括九宮的終態。
輸出
輸出最少的步數,假設不存在方案,則輸出-1。
例子輸入
12345678.
123.46758
例子輸出
3
#include <iostream> #include <cstring> #include <cstdio> #include <queue> using namespace std; char str1[20];///終態 int jc[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};///1到10的階乘 int dir[] = {0, 1, 0, -1, 0};///方向 bool f[1000000]; struct node {char str[10];//當然狀態int step;//步數int loc;//空格位置 }; int fun(char str[])//狀態匹配 {for (int i = 0; i < 9; i++) {if (str[i] != str1[i])return false;}return true; } int por(string a)//康托展開 {int size = 0;for (int i = 0; i < 9; i++) {int len = 0;for (int j = i + 1; j < 9; j++) {if (a[i] > a[j])len++;}size += len * jc[8 - i];}return size; } int bfs(node x) {queue<node>q;q.push(x);while (!q.empty()) {node a = q.front();q.pop();for (int i = 0; i < 4; i++) {//四個方向// cout<<a.str<<endl;node b = a;int ax = b.loc / 3 + dir[i];int ay = b.loc % 3 + dir[i + 1];if (ax < 0 || ax >= 3 || ay < 0 || ay >= 3)continue;b.str[b.loc] = b.str[ax * 3 + ay];//位置交換b.str[ax * 3 + ay] = '9';b.loc = ax * 3 + ay;b.step ++;int index = por(b.str);if (!f[index]) {if (fun(b.str)) {return b.step;}f[index] = true;q.push(b);}}}return -1; } int main() {node a;while (cin >> a.str >> str1) {memset(f, 0, sizeof(f));for (int i = 0; i < 9; i++){if (a.str[i] == '.') {a.str[i] = 9; a.loc = i; a.step = 0;}if(str1[i]=='.')str1[i]='9';}cout << bfs(a) << endl;}return 0; }
總結
- 上一篇: 【转载】selenium webdriv
- 下一篇: 弹窗效果处理和改进