[LeetCode] Sliding Puzzle

773. Sliding Puzzle

On an 2 x 3 board, there are five tiles labeled from 1 to 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 the puzzle board 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.

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
class Solution {
string find(vector<vector<int>> &b) {
string res;
for(int t = 0; t < 6; t++)
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if(b[i][j] == t) res += ((i * 3 + j) | 0b110000);
}
}
return res;
}
int findNextPosition(string& a, int val) {
for(int i = 0; i < 6; i++) if((a[i] & 0b111) == val) return i;
return -1;
}

public:
int slidingPuzzle(vector<vector<int>> &board) {
int res(1);
string goal = "501234", st = find(board);
if (st == goal) return 0;
unordered_set<string> v;
unordered_map<int, vector<int>> m = {{0, {1, 3}},
{1, {0, 2, 4}},
{2, {1, 5}},
{3, {0, 4}},
{4, {1, 3, 5}},
{5, {4, 2}}};
queue<string> q;
q.push(st);
v.insert(st);
while (!q.empty()) {
int size = q.size();
while (size--) {
auto cur = q.front();
q.pop();
for (auto target : m[cur[0] & 0b1111]) {
string next = cur;
int np = findNextPosition(next, target);
char tmp = next[np];
next[np] = next[0];
next[0] = tmp;
if(next == goal) return res;
if (!v.count(next)){
v.insert(next);
q.push(next);
}
}
}
res++;
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/27/PS/LeetCode/sliding-puzzle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.