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 59
| #include <iostream> #include <cstdio> #include <queue> #include <unordered_set> using namespace std; typedef pair <string, int> PSI; const string ed = "123804765"; const int dx[4] = { 1, -1, 0, 0 }, dy[4] = { 0, 0, 1, -1 }; queue <PSI> q; unordered_set <string> vis; bool inside (int x, int y) { return x >= 0 && x < 3 && y >= 0 && y < 3; } void bfs () { while (!q.empty()) { PSI t = q.front(); q.pop(); if (t.first == ed) { cout << t.second; return; } t.second++; int x, y; for (int i = 0; i < t.first.size(); i++) if (t.first[i] == '0') { x = i / 3; y = i % 3; break; } for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (!inside(nx, ny)) continue; swap(t.first[x * 3 + y], t.first[nx * 3 + ny]); if (!vis.count(t.first)) { q.push(t); vis.insert(t.first); } swap(t.first[x * 3 + y], t.first[nx * 3 + ny]); } } } int main () { string t; cin >> t; q.push(make_pair(t, 0)); bfs(); return 0; }
|