-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path752-open-the-lock.ts
37 lines (28 loc) · 950 Bytes
/
752-open-the-lock.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
type QueueItem = [string, number]
function openLock(deadends: string[], target: string): number {
const dead = new Set(deadends)
const visited = new Set<string>()
const queue: QueueItem[] = []
queue.push(['0000', 0])
visited.add('0000')
while (queue.length > 0) {
const [current, steps] = queue.shift()!
if(dead.has(current)) {
continue
}
if(current === target) {
return steps
}
for(let i = 0; i < 4; i++) {
for(let move of [-1,1]) {
const newSet = (parseInt(current[i], 10) + move + 10) % 10
const newState = current.substring(0, i) + newSet + current.substring(i + 1)
if(!visited.has(newState) && !dead.has(newState)) {
visited.add(newState)
queue.push([newState, steps + 1])
}
}
}
}
return -1
}