BFS explores a graph layer by layer, so the first time it reaches a vertex is along a shortest path. Track distance and predecessor while exploring, then walk predecessors 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 the predecessor of each vertex: 6 -> 5 -> 4 -> 2 -> 1, reversed.

Basic Implementation

basic.R
adj <- list("1" = c(2, 3), "2" = c(1, 4), "3" = c(1, 4), "4" = c(2, 3, 5), "5" = c(4, 6), "6" = c(5))
src <- 1
dst <- 6
dist <- list()
parent <- list()
dist[[as.character(src)]] <- 0
parent[[as.character(src)]] <- 0
queue <- c(src)
head <- 1
while (head <= length(queue)) {
	v <- queue[head]
	head <- head + 1
	for (nb in adj[[as.character(v)]]) {
		if (is.null(dist[[as.character(nb)]])) {
			dist[[as.character(nb)]] <- dist[[as.character(v)]] + 1
			parent[[as.character(nb)]] <- v
			queue[length(queue) + 1] <- nb
		}
	}
}
path <- integer(0)
node <- dst
while (node != 0) {
	path[length(path) + 1] <- node
	node <- parent[[as.character(node)]]
}
path <- rev(path)
cat("[", paste(path, collapse = ", "), "]\n", sep = "")
cat(dist[[as.character(dst)]], "\n", sep = "")

Complexity

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

Implementation notes

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