Skip to content

Commit fb4e70f

Browse files
committed
Add solution #773
1 parent 3351059 commit fb4e70f

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,7 @@
585585
768|[Max Chunks To Make Sorted II](./0768-max-chunks-to-make-sorted-ii.js)|Hard|
586586
769|[Max Chunks To Make Sorted](./0769-max-chunks-to-make-sorted.js)|Medium|
587587
770|[Basic Calculator IV](./0770-basic-calculator-iv.js)|Hard|
588+
773|[Sliding Puzzle](./0773-sliding-puzzle.js)|Hard|
588589
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
589590
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
590591
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|

solutions/0773-sliding-puzzle.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* 773. Sliding Puzzle
3+
* https://leetcode.com/problems/sliding-puzzle/
4+
* Difficulty: Hard
5+
*
6+
* On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by
7+
* 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
8+
*
9+
* The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
10+
*
11+
* Given the puzzle board board, return the least number of moves required so that the state of the
12+
* board is solved. If it is impossible for the state of the board to be solved, return -1.
13+
*/
14+
15+
/**
16+
* @param {number[][]} board
17+
* @return {number}
18+
*/
19+
var slidingPuzzle = function(board) {
20+
const target = '123450';
21+
const moves = [
22+
[1, 3], [0, 2, 4], [1, 5],
23+
[0, 4], [1, 3, 5], [2, 4]
24+
];
25+
26+
const start = board.flat().join('');
27+
if (start === target) return 0;
28+
29+
const queue = [[start, 0]];
30+
const seen = new Set([start]);
31+
32+
while (queue.length) {
33+
const [state, steps] = queue.shift();
34+
const index = state.indexOf('0');
35+
36+
for (const next of moves[index]) {
37+
const chars = state.split('');
38+
[chars[index], chars[next]] = [chars[next], chars[index]];
39+
const nextState = chars.join('');
40+
41+
if (nextState === target) return steps + 1;
42+
43+
if (!seen.has(nextState)) {
44+
seen.add(nextState);
45+
queue.push([nextState, steps + 1]);
46+
}
47+
}
48+
}
49+
50+
return -1;
51+
};

0 commit comments

Comments
 (0)