-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.go
71 lines (56 loc) · 1.39 KB
/
search.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package graph
// Each time a vertex is visited, the while function is triggered.
// The function exits if while returns false or there are no more vertices.
func BFS[K comparable](g Graph[K], entry K, while func(vertex K, depth uint) bool) error {
queue := []K{entry}
visited := make(map[K]struct{})
var depth, depthCounter uint
var depthThreshold uint = 1
for len(queue) > 0 {
bottom := queue[0]
queue = queue[1:]
if _, ok := visited[bottom]; ok {
depthThreshold--
continue
}
if !while(bottom, depth) {
return nil
}
n := g.Adjacency(bottom)
if n == nil {
return ErrNilVertex
}
queue = append(queue, n...)
visited[bottom] = struct{}{}
depthCounter++
if depthCounter == depthThreshold {
depth++
depthCounter = 0
depthThreshold = uint(len(queue))
}
}
return nil
}
// Each time a vertex is visited, the while function is triggered.
// The function exits if while returns false or there are no more vertices.
func DFS[K comparable](g Graph[K], entry K, while func(vertex K) bool) error {
queue := []K{entry}
visited := make(map[K]struct{})
for len(queue) > 0 {
top := queue[len(queue)-1]
queue = queue[:len(queue)-1]
if _, ok := visited[top]; ok {
continue
}
if !while(top) {
return nil
}
n := g.Adjacency(top)
if n == nil {
return ErrNilVertex
}
queue = append(queue, n...)
visited[top] = struct{}{}
}
return nil
}