-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.go
38 lines (30 loc) · 794 Bytes
/
bfs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package chapter6
type Graph struct {
Vertices map[string][]string
}
func NewGraph(vertices map[string][]string) *Graph {
return &Graph{
Vertices: vertices,
}
}
// BreadthFirstSearch implements Breadth-First Search (BFS) algorithm to find salesperson in graph.
func (g *Graph) BreadthFirstSearch(target string) bool {
searchQueue := make([]string, 0)
searchQueue = append(searchQueue, g.Vertices[target]...)
checked := make(map[string]bool)
for len(searchQueue) > 0 {
val := searchQueue[0]
searchQueue = searchQueue[1:]
if !checked[val] {
if isSalesperson(val) {
return true
}
searchQueue = append(searchQueue, g.Vertices[val]...)
checked[val] = true
}
}
return false
}
func isSalesperson(name string) bool {
return string(name[len(name)-1]) == "m"
}