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] with distance 4. The path is rebuilt from parent: 6 -> 5 -> 4 -> 2 -> 1, reversed.

Basic Implementation

basic.swift
var adj: [Int: [Int]] = [:]
adj[1] = [2, 3]
adj[2] = [1, 4]
adj[3] = [1, 4]
adj[4] = [2, 3, 5]
adj[5] = [4, 6]
adj[6] = [5]
let src = 1
let dst = 6
var dist: [Int: Int] = [src: 0]
var parent: [Int: Int] = [src: 0]
var queue: [Int] = [src]
while !queue.isEmpty {
	let v = queue.removeFirst()
	for nb in adj[v]! {
		if dist[nb] == nil {
			dist[nb] = dist[v]! + 1
			parent[nb] = v
			queue.append(nb)
		}
	}
}
var path: [Int] = []
var node = dst
while node != 0 {
	path.append(node)
	node = parent[node]!
}
print(Array(path.reversed()))
print(dist[dst]!)

Complexity

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

Implementation notes

  • Swift: a dist dictionary doubles as the visited check, parent records predecessors (0 marks the source), and an array 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.