Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 49d13b7

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

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

‎lcof2/剑指 Offer II 109. 开密码锁/README.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,47 @@ public:
236236
};
237237
```
238238
239+
#### Go
240+
241+
```go
242+
func openLock(deadends []string, target string) int {
243+
dead := map[string]bool{}
244+
for _, s := range deadends {
245+
dead[s] = true
246+
}
247+
if dead["0000"] {
248+
return -1
249+
}
250+
if target == "0000" {
251+
return 0
252+
}
253+
q := []string{"0000"}
254+
visited := map[string]bool{"0000": true}
255+
step := 0
256+
for len(q) > 0 {
257+
step++
258+
size := len(q)
259+
for i := 0; i < size; i++ {
260+
cur := q[0]
261+
q = q[1:]
262+
for j := 0; j < 4; j++ {
263+
for k := -1; k <= 1; k += 2 {
264+
next := cur[:j] + string((cur[j]-'0'+byte(k)+10)%10+'0') + cur[j+1:]
265+
if next == target {
266+
return step
267+
}
268+
if !dead[next] && !visited[next] {
269+
q = append(q, next)
270+
visited[next] = true
271+
}
272+
}
273+
}
274+
}
275+
}
276+
return -1
277+
}
278+
```
279+
239280
<!-- tabs:end -->
240281

241282
<!-- solution:end -->
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)

AltStyle によって変換されたページ (->オリジナル) /