Skip to content

Commit c4d7fe5

Browse files
committed
feat: add go solution to lcof2 problem: No.109 (doocs#3574)
1 parent 15492af commit c4d7fe5

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
func openLock(deadends []string, target string) int {
2+
dead := map[string]bool{}
3+
for _, s := range deadends {
4+
dead[s] = true
5+
}
6+
if dead["0000"] {
7+
return -1
8+
}
9+
if target == "0000" {
10+
return 0
11+
}
12+
q := []string{"0000"}
13+
visited := map[string]bool{"0000": true}
14+
step := 0
15+
for len(q) > 0 {
16+
step++
17+
size := len(q)
18+
for i := 0; i < size; i++ {
19+
cur := q[0]
20+
q = q[1:]
21+
for j := 0; j < 4; j++ {
22+
for k := -1; k <= 1; k += 2 {
23+
next := cur[:j] + string((cur[j]-'0'+byte(k)+10)%10+'0') + cur[j+1:]
24+
if next == target {
25+
return step
26+
}
27+
if !dead[next] && !visited[next] {
28+
q = append(q, next)
29+
visited[next] = true
30+
}
31+
}
32+
}
33+
}
34+
}
35+
return -1
36+
}

0 commit comments

Comments
 (0)