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
| class Solution { public: int slidingPuzzle(vector<vector<int>>& board) { int res = 0, m = board.size(), n = board[0].size(); string target = "123450", start; for (const auto &v : board) { for (char c : v) { start += '0' + c; } } vector<vector<int>> next{{1,3}, {0,2,4}, {1,5}, {0,4}, {1,3,5}, {2,4}}; unordered_set<string> visited{start}; queue<string> q{{start}}; while (!q.empty()) { for (int i = q.size(); i > 0; --i) { auto cur = q.front(); q.pop(); if (cur == target) return res; int zero_idx = cur.find("0"); for (int v : next[zero_idx]) { swap(cur[v], cur[zero_idx]); if (!visited.count(cur)) { visited.insert(cur); q.push(cur); } swap(cur[v], cur[zero_idx]); } } ++res; } return -1; } };
|