-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0752-open-the-lock.js
More file actions
56 lines (48 loc) · 1.58 KB
/
0752-open-the-lock.js
File metadata and controls
56 lines (48 loc) · 1.58 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
56
/**
* Open The Lock
* Time Complexity: O(N * L * E)
* Space Complexity: O(N * L)
*/
var openLock = function (deadends, target) {
const forbiddenCombinations = new Set(deadends);
const bfsQueue = [["0000", 0]];
const exploredStates = new Set(["0000"]);
if (forbiddenCombinations.has("0000")) {
return -1;
}
while (bfsQueue.length > 0) {
const [currentCombination, currentMoves] = bfsQueue.shift();
if (currentCombination === target) {
return currentMoves;
}
for (let wheelIndex = 0; wheelIndex < 4; wheelIndex++) {
const digitChar = currentCombination[wheelIndex];
const numericValue = parseInt(digitChar);
const incrementedDigit = (numericValue + 1) % 10;
const decrementedDigit = (numericValue - 1 + 10) % 10;
const combinationUp =
currentCombination.substring(0, wheelIndex) +
incrementedDigit.toString() +
currentCombination.substring(wheelIndex + 1);
if (
!exploredStates.has(combinationUp) &&
!forbiddenCombinations.has(combinationUp)
) {
bfsQueue.push([combinationUp, currentMoves + 1]);
exploredStates.add(combinationUp);
}
const combinationDown =
currentCombination.substring(0, wheelIndex) +
decrementedDigit.toString() +
currentCombination.substring(wheelIndex + 1);
if (
!exploredStates.has(combinationDown) &&
!forbiddenCombinations.has(combinationDown)
) {
bfsQueue.push([combinationDown, currentMoves + 1]);
exploredStates.add(combinationDown);
}
}
}
return -1;
};