-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
72 lines (67 loc) · 2.07 KB
/
Solution.cpp
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
62
63
64
65
66
67
68
69
70
71
72
class Solution {
public:
int slidingPuzzle(vector<vector<int>>& board) {
string start = gets(board);
string end = "123450";
if (start == end) return 0;
unordered_set<string> vis;
vis.insert(start);
queue<string> q{{start}};
int ans = 0;
while (!q.empty()) {
++ans;
for (int n = q.size(); n > 0; --n) {
string x = q.front();
q.pop();
setb(x, board);
for (string y : next(board)) {
if (y == end) return ans;
if (!vis.count(y)) {
vis.insert(y);
q.push(y);
}
}
}
}
return -1;
}
string gets(vector<vector<int>>& board) {
string s = "";
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j)
s.push_back('0' + board[i][j]);
return s;
}
void setb(string s, vector<vector<int>>& board) {
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j)
board[i][j] = s[i * 3 + j] - '0';
}
vector<string> next(vector<vector<int>>& board) {
vector<string> res;
auto p = find0(board);
int i = p.first, j = p.second;
vector<int> dirs = {-1, 0, 1, 0, -1};
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < 2 && y >= 0 && y < 3) {
swap(i, j, x, y, board);
res.push_back(gets(board));
swap(i, j, x, y, board);
}
}
return res;
}
void swap(int i, int j, int x, int y, vector<vector<int>>& board) {
int t = board[i][j];
board[i][j] = board[x][y];
board[x][y] = t;
}
pair<int, int> find0(vector<vector<int>>& board) {
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j)
if (board[i][j] == 0)
return {i, j};
return {0, 0};
}
};