题目:
On a 2x3 board
, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.
A move consists of choosing 0
and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board
is [[1,2,3],[4,5,0]].
Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.
Examples:
Input: board = [[1,2,3],[4,0,5]] Output: 1 Explanation: Swap the 0 and the 5 in one move.
Input: board = [[1,2,3],[5,4,0]] Output: -1 Explanation: No number of moves will make the board solved.
Input: board = [[4,1,2],[5,0,3]] Output: 5 Explanation: 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4,1,2],[5,0,3]] After move 1: [[4,1,2],[0,5,3]] After move 2: [[0,1,2],[4,5,3]] After move 3: [[1,0,2],[4,5,3]] After move 4: [[1,2,0],[4,5,3]] After move 5: [[1,2,3],[4,5,0]]
Input: board = [[3,2,4],[1,5,0]] Output: 14
Note:
board
will be a 2 x 3 array as described above.board[i][j]
will be a permutation of[0, 1, 2, 3, 4, 5]
.
思路:
涉及到最短步数的,一般就应该首先想到BFS了。我们从某个当前状态开始,计算它接下来的几个可能的状态,然后分别计算是否已经达到了目标。一旦达到了,就可以返回;否则就将它加入到当前队列中。
为了避免重复计算,我们定义一个名为visited的哈希表,记录截止当前已经出现过的状态。
代码:
class Solution {
public:
int slidingPuzzle(vector<vector<int>>& board) {
set<vector<vector<int>>> visited;
vector<vector<int>> target = {{1, 2, 3}, {4, 5, 0}};
queue<pair<vector<vector<int>>, int>> q;
q.push(make_pair(board, 0));
visited.insert(board);
while (!q.empty()) {
vector<vector<int>> b = q.front().first;
int s = q.front().second;
q.pop();
if (b == target) {
return s;
}
list<vector<vector<int>>> neighbors;
getNeighbors(b, neighbors);
for (auto it = neighbors.begin(); it != neighbors.end(); ++it) {
if (visited.find(*it) == visited.end()) {
visited.insert(*it);
q.push(make_pair(*it, s + 1));
}
}
}
return -1;
}
private:
void getNeighbors(vector<vector<int>> &b, list<vector<vector<int>>> &neighbors) {
int r0 = -1, c0 = -1;
for (int r = 0; r < 2; ++r) {
for (int c = 0; c < 3; ++c) {
if (b[r][c] == 0) {
r0 = r, c0 = c;
break;
}
}
}
vector<vector<int>> dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < 4; ++i) {
int r = r0 + dir[i][0], c = c0 + dir[i][1];
if (r >= 0 && r < 2 && c >= 0 && c < 3) {
neighbors.push_back(b);
swap(neighbors.back()[r0][c0], neighbors.back()[r][c]);
}
}
}
};