BFS explores a graph layer by layer, so the first time it reaches a vertex is along a shortest path. Track dist[v] and parent[v] while exploring, then walk parents back from the target to reconstruct the route.

Algorithm

On the canonical graph from graph-adjacency-list, the shortest path from 1 to 6 is [1 2 4 5 6] (space-separated) with distance 4. The path is rebuilt from parent: 6 -> 5 -> 4 -> 2 -> 1, reversed.

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},
	}
	src := 1
	dst := 6
	dist := map[int]int{src: 0}
	parent := map[int]int{src: 0}
	queue := []int{src}
	for len(queue) > 0 {
		v := queue[0]
		queue = queue[1:]
		for _, nb := range adj[v] {
			if _, ok := dist[nb]; !ok {
				dist[nb] = dist[v] + 1
				parent[nb] = v
				queue = append(queue, nb)
			}
		}
	}
	path := []int{}
	for node := dst; node != 0; node = parent[node] {
		path = append(path, node)
	}
	for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
		path[i], path[j] = path[j], path[i]
	}
	fmt.Println(path)
	fmt.Println(dist[dst])
}

Complexity

  • Time: O(V + E)
  • Space: O(V)

Implementation notes

  • Go: a dist map doubles as the visited check, parent records predecessors (0 marks the source), and a slice index walks the queue.
  • The replay shows dist, parent, and the queue filling in, then the reconstructed path, matching the lesson spec.
layers equal distance BFS order equals distance in an unweighted graph.