Skip to content

feat: add go solution to lcof2 problem: No.109 (#3574) #3574

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions lcof2/剑指 Offer II 109. 开密码锁/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,47 @@ public:
};
```

#### Go

```go
func openLock(deadends []string, target string) int {
dead := map[string]bool{}
for _, s := range deadends {
dead[s] = true
}
if dead["0000"] {
return -1
}
if target == "0000" {
return 0
}
q := []string{"0000"}
visited := map[string]bool{"0000": true}
step := 0
for len(q) > 0 {
step++
size := len(q)
for i := 0; i < size; i++ {
cur := q[0]
q = q[1:]
for j := 0; j < 4; j++ {
for k := -1; k <= 1; k += 2 {
next := cur[:j] + string((cur[j]-'0'+byte(k)+10)%10+'0') + cur[j+1:]
if next == target {
return step
}
if !dead[next] && !visited[next] {
q = append(q, next)
visited[next] = true
}
}
}
}
}
return -1
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
36 changes: 36 additions & 0 deletions lcof2/剑指 Offer II 109. 开密码锁/Solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
func openLock(deadends []string, target string) int {
dead := map[string]bool{}
for _, s := range deadends {
dead[s] = true
}
if dead["0000"] {
return -1
}
if target == "0000" {
return 0
}
q := []string{"0000"}
visited := map[string]bool{"0000": true}
step := 0
for len(q) > 0 {
step++
size := len(q)
for i := 0; i < size; i++ {
cur := q[0]
q = q[1:]
for j := 0; j < 4; j++ {
for k := -1; k <= 1; k += 2 {
next := cur[:j] + string((cur[j]-'0'+byte(k)+10)%10+'0') + cur[j+1:]
if next == target {
return step
}
if !dead[next] && !visited[next] {
q = append(q, next)
visited[next] = true
}
}
}
}
}
return -1
}
Loading