MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / BreadthFirstSearch

Function BreadthFirstSearch

graph/breadthfirstsearch.go:9–28  ·  view source on GitHub ↗

BreadthFirstSearch is an algorithm for traversing and searching graph data structures. It starts at an arbitrary node of a graph, and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. Worst-case performance O(|V|+|E|)=O(b^{d})}O(|V|+|

(start, end, nodes int, edges [][]int)

Source from the content-addressed store, hash-verified

7// Worst-case space complexity O(|V|)=O(b^{d})}O(|V|)=O(b^{d}) where |V| is the number of vertices and |E| is the number of edges in the graph and b is the branching factor of the graph (the average number of successors of a node). d is the depth of the goal node.
8// reference: https://en.wikipedia.org/wiki/Breadth-first_search
9func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int) {
10 queue := make([]int, 0)
11 discovered := make([]int, nodes)
12 discovered[start] = 1
13 queue = append(queue, start)
14 for len(queue) > 0 {
15 v := queue[0]
16 queue = queue[1:]
17 for i := 0; i < len(edges[v]); i++ {
18 if discovered[i] == 0 && edges[v][i] > 0 {
19 if i == end {
20 return true, discovered[v]
21 }
22 discovered[i] = discovered[v] + 1
23 queue = append(queue, i)
24 }
25 }
26 }
27 return false, 0
28}

Callers 1

TestBreadthFirstSearchFunction · 0.85

Calls

no outgoing calls

Tested by 1

TestBreadthFirstSearchFunction · 0.68