-
Notifications
You must be signed in to change notification settings - Fork 0
/
breathfirstsearch.go
54 lines (45 loc) · 1.02 KB
/
breathfirstsearch.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
package graph
import (
"github.com/zawlinnnaing/data-structures-algorithms-go/src/queue"
"github.com/zawlinnnaing/data-structures-algorithms-go/src/slice"
)
type AdjacencyMatrix = [][]int
func BreathFirstSearch(matrix AdjacencyMatrix, source int, needle int) []int {
queue := queue.NewQueue[int]()
seen := make([]bool, len(matrix))
prev := make([]int, len(matrix))
seen[source] = true
queue.Push(source)
for idx := range prev {
prev[idx] = -1
}
for queue.Length() > 0 {
current := queue.Pop()
if current == needle {
break
}
connections := matrix[current]
for childIdx := range connections {
if seen[childIdx] {
continue
}
if connections[childIdx] == 0 {
continue
}
queue.Push(childIdx)
seen[childIdx] = true
prev[childIdx] = current
}
}
if prev[needle] == -1 {
return []int{}
}
current := needle
out := slice.NewMutable[int]()
for prev[current] != -1 {
out.Push(current)
current = prev[current]
}
out.Reverse()
return append([]int{source}, out.Elements()...)
}