-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0773-sliding-puzzle.js
More file actions
55 lines (46 loc) · 1.41 KB
/
0773-sliding-puzzle.js
File metadata and controls
55 lines (46 loc) · 1.41 KB
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
/**
* Sliding Puzzle
* Time Complexity: O(N! * L)
* Space Complexity: O(N! * L)
*/
var slidingPuzzle = function (board) {
const targetPuzzleState = "123450";
const validZeroMoves = [
[1, 3],
[0, 2, 4],
[1, 5],
[0, 4],
[1, 3, 5],
[2, 4],
];
const startingBoardLayout = board.flat().join("");
if (startingBoardLayout === targetPuzzleState) {
return 0;
}
const bfsTraversalQueue = [[startingBoardLayout, 0]];
const exploredStates = new Set([startingBoardLayout]);
while (bfsTraversalQueue.length > 0) {
const [currentBoardConfiguration, totalMovesMade] =
bfsTraversalQueue.shift();
const zeroTileIndex = currentBoardConfiguration.indexOf("0");
for (const adjacentTileIndex of validZeroMoves[zeroTileIndex]) {
const boardCharacterArray = currentBoardConfiguration.split("");
[
boardCharacterArray[zeroTileIndex],
boardCharacterArray[adjacentTileIndex],
] = [
boardCharacterArray[adjacentTileIndex],
boardCharacterArray[zeroTileIndex],
];
const nextBoardStateString = boardCharacterArray.join("");
if (nextBoardStateString === targetPuzzleState) {
return totalMovesMade + 1;
}
if (!exploredStates.has(nextBoardStateString)) {
exploredStates.add(nextBoardStateString);
bfsTraversalQueue.push([nextBoardStateString, totalMovesMade + 1]);
}
}
}
return -1;
};