forked from shellfly/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbreadth_first_paths.go
50 lines (45 loc) · 924 Bytes
/
breadth_first_paths.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
package algs4
// BreadFirstPaths ...
type BreadFirstPaths struct {
marked []bool
edgeTo []int
s int
}
// NewBreadFirstPaths ...
func NewBreadFirstPaths(g *Graph, s int) *BreadFirstPaths {
b := &BreadFirstPaths{marked: make([]bool, g.V()), edgeTo: make([]int, g.V()), s: s}
b.Bfs(g, s)
return b
}
// Bfs ...
func (s *BreadFirstPaths) Bfs(g *Graph, v int) {
s.marked[v] = true
queue := NewQueue()
queue.Enqueue(v)
for !queue.IsEmpty() {
v := queue.Dequeue().(int)
for _, w := range g.Adj(v) {
if !s.marked[w] {
s.edgeTo[w] = v
s.marked[w] = true
queue.Enqueue(w)
}
}
}
}
// HasPathTo ...
func (s *BreadFirstPaths) HasPathTo(v int) bool {
return s.marked[v]
}
// PathTo ...
func (s *BreadFirstPaths) PathTo(v int) []int {
if !s.HasPathTo(v) {
return nil
}
path := NewStack()
for x := v; x != s.s; x = s.edgeTo[x] {
path.Push(x)
}
path.Push(s.s)
return path.IntSlice()
}