-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution-normal.ts
80 lines (58 loc) · 1.68 KB
/
solution-normal.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
78
79
80
/*
* @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 => {
// * inspired by https://leetcode-cn.com/problems/open-the-lock/solution/javascript-72ms-by-zxy7/
// * his answer is actually super slow ( 1464 ms )
// * Mine is faster ( 384 ms )
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 curArr = cur.split('');
const neighbors: Code[] = [];
// * try mutate
for (let i = 0; i < 4; i++) {
const char = cur[i];
curArr[i] = char === '9' ? '0' : String(Number(char) + 1);
neighbors.push(curArr.join(''));
curArr[i] = char === '0' ? '9' : String(Number(char) - 1);
neighbors.push(curArr.join(''));
curArr[i] = char;
}
return neighbors.filter((e) => steps[e] === undefined);
};
// * ---------------- 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 };