-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
58 lines (51 loc) · 1.5 KB
/
solution.js
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
/**
* @param {string[]} deadends
* @param {string} target
* @return {number}
*/
// BFS
var openLock = function (deadends, target) {
const deadMap = {};
for (let i = 0; i < deadends.length; i++) {
deadMap[deadends[i]] = true;
}
if (deadMap['0000'] || deadends[target]) {
return -1;
}
const usedMap = {
'0000': true,
};
let sequence = [
'0000', ];
let result = 0;
while (true) {
if (sequence.length === 0) {
return -1;
}
const nextSequence = [];
for (let i = 0; i < sequence.length; i++) {
if (sequence[i] === target) {
return result;
}
const num = sequence[i];
for (let j = 0; j < 4; j++) {
// 构造相邻接点
const prefix = num.substring(0, j);
const suffix = num.substring(j + 1);
const digit = +num[j];
const num1 = `${prefix}${digit === 9 ? '0' : digit + 1}${suffix}`;
const num2 = `${prefix}${digit === 0 ? '9' : digit - 1}${suffix}`;
if (!usedMap[num1] && !deadMap[num1]) {
usedMap[num1] = true;
nextSequence.push(num1);
}
if (!usedMap[num2] && !deadMap[num2]) {
usedMap[num2] = true;
nextSequence.push(num2);
}
}
}
sequence = nextSequence;
result++;
}
};