算法inGolang:Breadth-firstsearch(BFS、广度优先搜索)最短路径问题Shortest-pathproblem从A到F点有多条路径解决问题的算法Breadth-firstSearch(广度优先搜索)将问题建模为图(Graph)通过B
图是用来对不同事物间如何关联进行建模的一种方式
图是一种数据结构
找到名为 Tom 的朋友
~/Code/go via 🐹 v1.20.3 via 🅒 base
➜ mcd breadth_first_search
Code/go/breadth_first_search via 🐹 v1.20.3 via 🅒 base
➜ go mod init breadth_first_search
go: creating new go.mod: module breadth_first_search
Code/go/breadth_first_search via 🐹 v1.20.3 via 🅒 base
➜ c
Code/go/breadth_first_search via 🐹 v1.20.3 via 🅒 base
➜
package main
import "fmt"
type GraphMap map[string][]string
func main() {
var graphMap GraphMap = make(GraphMap, 0)
graphMap["you"] = []string{"alice", "bob", "claire"}
graphMap["bob"] = []string{"anuj", "peggy"}
graphMap["alice"] = []string{"peggy"}
graphMap["claire"] = []string{"tom", "johnny"}
graphMap["anuj"] = []string{}
graphMap["peggy"] = []string{}
graphMap["tom"] = []string{}
graphMap["johnny"] = []string{}
search_queue := graphMap["you"]
for {
if len(search_queue) > 0 {
var person string
person, search_queue = search_queue[0], search_queue[1:]
if personIsTom(person) {
fmt.Printf("%s is already in the queue for you.\n", person)
break
} else {
search_queue = append(search_queue, graphMap[person]...)
}
} else {
fmt.Println("Not found in search queue")
break
}
}
}
func personIsTom(p string) bool {
return p == "tom"
}
Code/go/breadth_first_search via 🐹 v1.20.3 via 🅒 base
➜ go run main.go
tom is already in the queue for you.
Code/go/breadth_first_search via 🐹 v1.20.3 via 🅒 base took 3.2s
➜
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!