1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include <bits/stdc++.h> using namespace std;
typedef pair<string, pair<int, int>> PI; const int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; string a, b = "123804765";
int extend(queue<PI> &aq, queue<PI> &bq, unordered_map<string, bool> &av, unordered_map<string, bool> &bv) { int sz = aq.size(); while (sz--) { string str = aq.front().first; int z = aq.front().second.first, step = aq.front().second.second; aq.pop(); for (int i = 0; i < 4; ++i) { int nx = (z / 3) + dx[i], ny = (z % 3) + dy[i]; if (nx < 0 || ny < 0 || nx > 2 || ny > 2) continue; string ns = str; int nz = nx * 3 + ny; swap(ns[z], ns[nz]); if (bv.count(ns)) return step + bq.front().second.second + 1; if (av.count(ns)) continue; av[ns] = 1; aq.push({ns, {nz, step + 1}}); } } return -1; }
int bfs() { if (a == b) return 0; queue<PI> aq, bq; unordered_map<string, bool> av, bv; for (int i = 0; i < a.length(); ++i) { if (a[i] == '0') { aq.push({a, {i, 0}}); break; } } bq.push({b, {4, 0}}); av[a] = bv[b] = 1; int res; while (aq.size() && bq.size()) { if (aq.size() < bq.size()) { res = extend(aq, bq, av, bv); } else { res = extend(bq, aq, bv, av); } if (~res) break; } return res; }
int main() { cin >> a; cout << bfs(); return 0; }
|