#include #include #include using namespace std; int dir[] = {1, -1, 2, -2}; unordered_map dist; string S = "12345678X", T = "87654321X"; int bfs() { queue q; q.push(S); dist[S] = 0; while (q.size()) { string t = q.front(); q.pop(); if (t == T) return dist[t]; int k = t.find('X'), distance = dist[t]; for (int i = 0; i < 4; i++) { swap(t[k], t[(k + dir[i] + 9) % 9]); if (!dist.count(t)) { q.push(t); dist[t] = distance + 1; } swap(t[k], t[(k + dir[i] + 9) % 9]); } } return -1; } int main() { cout << bfs() << endl; return 0; }