class Solution {
public:
int slidingPuzzle(vector<vector<int>>& board) {
unordered_set<int> visited;
priority_queue<tuple<int, int, int>> maxHeap; // {-moves, board, idx}
int idx = 0, value = 0;
for (int i = 5; i >= 0; --i) {
if (board[i / 3][i % 3] == 0) idx = i;
value = 10 * value + board[i / 3][i % 3];
}
visited.insert(value);
maxHeap.emplace(0, value, idx);
vector<vector<int>> direction = {
{1, 3},
{0, 2, 4},
{1, 5},
{0, 4},
{1, 3, 5},
{2, 4},
};
while (maxHeap.size()) {
auto [moves, current, idx] = maxHeap.top();
maxHeap.pop();
if (current == 54321) return -moves;
int p10idx = pow(10, idx);
for (auto nidx : direction[idx]) {
int p10nidx = pow(10, nidx);
int v = (current / p10nidx) % 10;
int next = current + v * (p10idx - p10nidx);
if (visited.count(next)) continue;
visited.insert(next);
maxHeap.emplace(moves - 1, next, nidx);
}
}
return -1;
}
};