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 60 61
| #include <iostream> #include <cstring> #include <unordered_map> #include <queue>
using namespace std;
int bfs(string start){ string end = "12345678x"; unordered_map <string, int> d; queue<string> q; q.push(start); d[start] = 0; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, -1, 0, 1}; while(q.size()){ auto t = q.front(); q.pop(); int distance = d[t]; if(t == end) return distance; int k = t.find('x'); int x = k / 3, y = k % 3; for(int i = 0; i < 4; ++i){ int a = x + dx[i], b = y + dy[i]; if(a >= 0 && a < 3 && b >= 0 && b < 3){ swap(t[k], t[a * 3 + b]); if(!d.count(t)){ d[t] = distance + 1; q.push(t); } swap(t[k], t[a * 3 + b]); } } } return -1; }
int main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); string start; for(int i = 0; i < 9; ++i){ char c; cin >> c; start += c; } cout << bfs(start) << endl; return 0; }
|