-
Notifications
You must be signed in to change notification settings - Fork 1
/
breadthFirstSearch.go
49 lines (41 loc) · 1.06 KB
/
breadthFirstSearch.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
package breadthFirstSearch
// Node is an element in a graph
type Node struct {
Value int
Parent *Node
Neighbours []*Node
}
// BreadthFirstSearch performs a breadth first search on a graph or tree
func BreadthFirstSearch(root *Node, target *Node) *Node {
// set root to nil
if root == nil {
return nil
}
// create a queue to store nodes
var visited []*Node
queue := []*Node{root}
// loop until queue is empty
for len(queue) > 0 {
// dequeue the first node
node := queue[0]
// remove the first node from the queue and return it
queue = queue[1:]
// check if the node is the target
if node.Value == target.Value {
return node // return the node
}
// add the node to the visited list
_ = append(visited, node)
// add the node's neighbours to the queue
for _, neighbour := range node.Neighbours {
// append the neighbour to the queue if it is not already in the queue
for _, n := range queue {
if n != neighbour {
queue = append(queue, neighbour)
}
}
}
}
// return nil if the target was not found
return nil
}