-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution-naive.ts
77 lines (58 loc) · 1.5 KB
/
solution-naive.ts
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* @lc app=leetcode id=752 lang=javascript
*
* [752] Open the Lock
*/
// @lc code=start
/**
* @param {string[]} deadends
* @param {string} target
* @return {number}
*/
const openLock = (deadends: string[], target: string): number => {
// * first version, passed 552ms, not so good
if (deadends.includes('0000') || deadends.includes(target)) return -1;
if (target === '0000') return 0;
// * ---------------- prepare
type Code = string;
const steps: Record<Code, number> = { '0000': 0 };
deadends.forEach((code) => {
steps[code] = -1;
});
// * ---------------- bfsWalker
const bfsWalker = (cur: Code): Code[] => {
const [a, b, c, d] = cur.split('').map((e) => Number(e));
const neighbors = [
[a + 1, b, c, d],
[a - 1, b, c, d],
[a, b + 1, c, d],
[a, b - 1, c, d],
[a, b, c + 1, d],
[a, b, c - 1, d],
[a, b, c, d + 1],
[a, b, c, d - 1],
]
.map((e) => e.map((j) => (j + 10) % 10).join(''))
.filter((e) => steps[e] === undefined);
return neighbors;
};
// * ---------------- start searching
const queue: Code[] = ['0000'];
let cur: Code;
while (queue.length) {
cur = queue.shift()!;
const nextStep = steps[cur] + 1;
if (cur === target) {
steps[target] = nextStep - 1;
break;
}
const neighbors = bfsWalker(cur);
neighbors.forEach((e) => {
steps[e] = nextStep;
queue.push(e);
});
}
return steps[target] ?? -1;
};
// @lc code=end
export { openLock };