Skip to content

Commit 95552d4

Browse files
committed
add sliding puzzle script.
1 parent 9a6a3de commit 95552d4

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

773-sliding-puzzle.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* @param {number[][]} board
3+
* @return {number}
4+
*/
5+
const slidingPuzzle = function(board) {
6+
const target = "123450";
7+
let start = "";
8+
for (let i = 0; i < board.length; i++) {
9+
for (let j = 0; j < board[0].length; j++) {
10+
start += board[i][j];
11+
}
12+
}
13+
const visited = {};
14+
// all the positions 0 can be swapped to
15+
const dirs = [[1, 3], [0, 2, 4], [1, 5], [0, 4], [1, 3, 5], [2, 4]];
16+
const queue = [];
17+
queue.push(start);
18+
visited[start] = true;
19+
let res = 0;
20+
while (queue.length !== 0) {
21+
// level count, has to use size control here, otherwise not needed
22+
let size = queue.length;
23+
for (let i = 0; i < size; i++) {
24+
let cur = queue.shift();
25+
if (cur === target) {
26+
return res;
27+
}
28+
let zero = cur.indexOf("0");
29+
// swap if possible
30+
for (let dir of dirs[zero]) {
31+
let next = swap(cur, zero, dir);
32+
if (visited.hasOwnProperty(next)) {
33+
continue;
34+
}
35+
visited[next] = true;
36+
queue.push(next);
37+
}
38+
}
39+
res++;
40+
}
41+
return -1;
42+
};
43+
44+
function swap(str, i, j) {
45+
const arr = str.split("");
46+
const ic = str[i];
47+
const jc = str[j];
48+
arr.splice(i, 1, jc);
49+
arr.splice(j, 1, ic);
50+
return arr.join("");
51+
}

0 commit comments

Comments
 (0)