1
var openLock = function (deadends, target) {
2
if (deadends.includes("0000")) {
3
return -1;
4
}
5
// treat deadends like visited
6
// if a number is in visited/deadends, simply ignore it
7
const visited = new Set(deadends);
8

9
const queue = [["0000", 0]];
10
visited.add("0000");
11

12
while (queue.length) {
13
const [cur, count] = queue.shift();
14
if (cur === target) {
15
return count;
16
}
17

18
// each number will create 8 more different paths to check
19

20
// e.g. if cur = 0000. 8 next/prev numbers to check are
21
// 1000, 9000, 0100, 0900, 0010, 0090, 0001, 0009
22
for (let i = 0; i < 4; i++) {
23
const c = cur[i];
24

25
let up = Number(c) + 1;
26
let down = Number(c) - 1;
27
// if up is 9, then up + 1 = 10 -> set it to 0
28
if (up === 10) {
29
up = "0";
30
}
31
// if down is 0. then down - 1 = -1 -> set to 9
32
if (down === -1) {
33
down = "9";
34
}
35

36
const next = cur.substring(0, i) + up + cur.substring(i + 1);
37
const prev = cur.substring(0, i) + down + cur.substring(i + 1);
38

39
// if not visited, push to queue
40
if (!visited.has(next)) {
41
visited.add(next);
42
queue.push([next, count + 1]);
43
}
44

45
if (!visited.has(prev)) {
46
visited.add(prev);
47
queue.push([prev, count + 1]);
48
}
49
}
50
}
51

52
return -1;
53
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0