BFS
Breadth-first search visits a graph or tree level by level using a queue. The first time you reach a node is a shortest path in an unweighted graph.
Detailed Explanation
You start at a node, visit its neighbours, then their neighbours, and so on. A slice used as a queue holds the frontier. A map or a []bool marks visited nodes so you do not enqueue them twice. Because you expand in distance order, the first time you pop the target, the number of edges you walked is minimal.
The queue in Go. var q []T plus q = append(q, v) to enqueue and v, q := q[0], q[1:] to dequeue. Dequeuing from the front of a slice is O(n) per pop if you shift, but with a head index (i++) unused prefixes stay in capacity — for a large BFS, use a growing head and do not q = q[1:] every time if n is huge, or accept O(n) extra leftover and clip occasionally. A container/list queue is O(1) push/pop and slower per operation. For typical graphs, a slice plus a head index is enough.
Graphs as adjacency lists. [][]int for nodes 0..n-1, or map[string][]string for named nodes. Trees are graphs without cycles; you still mark the parent if the tree is stored as bidirectional edges.
Grid BFS. A maze is a graph of cells. Neighbours are up/down/left/right if in bounds and not a wall. Flatten (r,c) to r*cols+c for a []bool visited, or use a [2]int key in a map.
What it costs. Time O(V+E). Space O(V) for the queue and visited set. BFS is the default for unweighted shortest path. For weighted edges, use Dijkstra and a heap, not BFS.
Code Examples
package main
import "fmt"
func bfs(adj [][]int, start int) []int {
dist := make([]int, len(adj))
for i := range dist {
dist[i] = -1
}
dist[start] = 0
q := []int{start}
for head := 0; head < len(q); head++ {
u := q[head]
for _, v := range adj[u] {
if dist[v] != -1 {
continue
}
dist[v] = dist[u] + 1
q = append(q, v)
}
}
return dist
}
func main() {
adj := [][]int{{1, 2}, {0}, {0}}
fmt.Println(bfs(adj, 0))
}Common Gotchas
BFS distance is edges, not weights
a cheap long path vs an expensive short path needs Dijkstra.
Mark visited when you enqueue, not when you dequeue
otherwise the same node can sit in the queue many times.
Forgetting visited / dist checks revisits nodes and can loop forever on a cycle
Forgetting visited / dist checks revisits nodes and can loop forever on a cycle