Graphs
Breadth-First Search
From a start vertex, explore the graph layer by layer. Use a queue and a "visited" set. Dequeue a vertex, visit it, enqueue all unvisited neighbours.
Algorithm
Canonical adjacency list:
1 -> [2, 3]
2 -> [1, 4]
3 -> [1, 4]
4 -> [2, 3, 5]
5 -> [4, 6]
6 -> [5]
Starting at vertex 1, the BFS visit order is [1, 2, 3, 4, 5, 6].
Basic Implementation
basic.go
package main
import "fmt"
func main() {
adj := map[int][]int{
1: {2, 3},
2: {1, 4},
3: {1, 4},
4: {2, 3, 5},
5: {4, 6},
6: {5},
}
start := 1
visited := map[int]bool{start: true}
queue := []int{start}
order := []int{}
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
order = append(order, v)
for _, nb := range adj[v] {
if !visited[nb] {
visited[nb] = true
queue = append(queue, nb)
}
}
}
fmt.Println(order)
}
Complexity
- Time: O(V + E)
- Space: O(V)
Implementation notes
- Go:
map[int][]intis the idiomatic adjacency list and keeps the vertex iteration shape visible; the lesson does not lean oncontainer/listor any third-party graph package. - A
map[int]boolis the explicit "visited" set; the queue is a plain[]intslice withqueue[0]/queue[1:]for dequeue andappendfor enqueue. - The replay prints the dequeued vertex, the queue, the visited set, and the running visit order each frame.
queue
A plain `[]int` slice with `queue[0]` / `queue = queue[1:]` for dequeue and `append` for enqueue implements FIFO without hiding the iteration shape.
visited-before-enqueue
Mark a vertex visited before pushing it onto the queue. Keeps the queue size bounded by V.