-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbfs.go
53 lines (40 loc) · 969 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package melichallenge
import "container/list"
type bfs struct {
graph *graph
initVertice int
targetVertices map[int]int
}
func (b *bfs) shortestPath() *list.List {
marked := make([]bool, b.graph.vertices)
edgeTo := make([]int, b.graph.vertices)
queue := new(queue)
targetFound := false
var target int
queue.enqueue(b.initVertice)
marked[b.initVertice] = true
for queue.size > 0 && !targetFound {
currentVertice := queue.dequeue().(int)
adjacents := b.graph.adjacents(currentVertice)
for e := adjacents.Front(); e != nil; e = e.Next() {
v := e.Value.(int)
if !marked[v] {
marked[v] = true
edgeTo[v] = currentVertice
queue.enqueue(v)
}
if _, ok := b.targetVertices[v]; ok {
targetFound = true
target = v
}
}
}
result := new(list.List)
if targetFound {
result.PushFront(target)
for v := edgeTo[target]; v != b.initVertice; v = edgeTo[v] {
result.PushFront(v)
}
}
return result
}