1 Star 0 Fork 0

catyMap/AlgorithmNote

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
openLock.go 1.05 KB
Copy Edit Raw Blame History
catyMap authored 2021-06-26 22:29 +08:00 . 添加BFS用例
package openlock
import "fmt"
func openLock(deadends []string, target string) int {
deads := make(map[string]int)
for _, v := range deadends {
deads[v]++
}
queue := make([]string, 0, 0)
queue = append(queue, "0000")
step := 0
for len(queue) != 0 {
size := len(queue)
for i := 0; i < size; i++ {
// 出队
top := queue[0]
queue = queue[1:]
if _, dead := deads[top]; dead {
continue
}
if top == target {
return step
}
fmt.Println(top)
deads[top]++
for j := 0; j < 4; j++ {
nodeUp := clickUp(top, j)
nodeDown := clickDown(top, j)
queue = append(queue, nodeUp, nodeDown)
}
}
step++
}
return -1
}
func clickUp(code string, idx int) string {
decodes := []byte(code)
ch := decodes[idx]
if ch == '9' {
decodes[idx] = '0'
return string(decodes)
}
ch++
decodes[idx] = ch
return string(decodes)
}
func clickDown(code string, idx int) string {
decodes := []byte(code)
ch := decodes[idx]
if ch == '0' {
decodes[idx] = '9'
return string(decodes)
}
ch--
decodes[idx] = ch
return string(decodes)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dogemap/algorithm-note.git
git@gitee.com:dogemap/algorithm-note.git
dogemap
algorithm-note
AlgorithmNote
dc486f96f6c1

Search