forked from wufenggirl/LeetCode-in-Golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
open-the-lock.go
executable file
·69 lines (61 loc) · 1.21 KB
/
open-the-lock.go
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
package problem0752
func openLock(deadends []string, target string) int {
isDeadends := dealDeadends(deadends)
return bfs(convert(target), isDeadends)
}
func bfs(target [4]int, isDeadends map[[4]int]bool) int {
queue := [][4]int{convert("0000")}
if isDeadends[queue[0]] {
return -1
}
if target == queue[0] {
return 0
}
isChecked := make(map[[4]int]bool, 1e4)
isChecked[queue[0]] = true
leng := 1
count := 1
for len(queue) > 0 {
if count == 0 {
leng++
count = len(queue)
}
for i := 0; i < 4; i++ {
a := queue[0]
a[i] = (a[i] + 9) % 10
if !isDeadends[a] && !isChecked[a] {
if a == target {
return leng
}
queue = append(queue, a)
isChecked[a] = true
}
b := queue[0]
b[i] = (b[i] + 1) % 10
if !isDeadends[b] && !isChecked[b] {
if b == target {
return leng
}
queue = append(queue, b)
isChecked[b] = true
}
}
queue = queue[1:]
count--
}
return -1
}
func dealDeadends(deadends []string) map[[4]int]bool {
res := make(map[[4]int]bool, len(deadends))
for _, d := range deadends {
res[convert(d)] = true
}
return res
}
func convert(s string) [4]int {
res := [4]int{}
for i := range res {
res[i] = int(s[i] - '0')
}
return res
}