diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/README.md" index 906d152fed407..d4b88475a5771 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/README.md" @@ -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 +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/Solution.go" "b/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/Solution.go" new file mode 100644 index 0000000000000..e150cc42225e8 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/Solution.go" @@ -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 +} \ No newline at end of file