Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 51f3ee9

Browse files
773. Sliding Puzzle
1 parent 0ad8f17 commit 51f3ee9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎sliding-puzzle.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Runtime: 8 ms
2+
// Memory Usage: 10 MB
3+
class Solution {
4+
public:
5+
int slidingPuzzle(vector<vector<int>>& board) {
6+
string src = "";
7+
for (auto a : board) {
8+
for (auto b : a) {
9+
src += to_string(b);
10+
}
11+
}
12+
set<string> vis;
13+
vis.insert(src);
14+
queue<string> q;
15+
q.push(src);
16+
vector<vector<int> > swps = {{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {3, 1, 5}, {2, 4}};
17+
int depth = 0;
18+
string target = "123450";
19+
while (!q.empty()) {
20+
int sz = q.size();
21+
for (int i = 0; i < sz; i++) {
22+
src = q.front();
23+
q.pop();
24+
if (src == target) return depth;
25+
int zero = src.find('0');
26+
for (int s : swps[zero]) {
27+
swap(src[zero], src[s]);
28+
if (vis.find(src) == vis.end()) {
29+
vis.insert(src);
30+
q.push(src);
31+
}
32+
swap(src[s], src[zero]);
33+
}
34+
}
35+
depth++;
36+
}
37+
return -1;
38+
}
39+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /