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.php
<?php
$adj = [1 => [2, 3], 2 => [1, 4], 3 => [1, 4], 4 => [2, 3, 5], 5 => [4, 6], 6 => [5]];
$src = 1;
$dst = 6;
$dist = [$src => 0];
$parent = [$src => null];
$queue = [$src];
$head = 0;
while ($head < count($queue)) {
	$v = $queue[$head];
	$head = $head + 1;
	foreach ($adj[$v] as $nb) {
		if (!array_key_exists($nb, $dist)) {
			$dist[$nb] = $dist[$v] + 1;
			$parent[$nb] = $v;
			$queue[] = $nb;
		}
	}
}
$path = [];
$node = $dst;
while ($node !== null) {
	$path[] = $node;
	$node = $parent[$node];
}
$path = array_reverse($path);
echo "[" . implode(", ", $path) . "]\n";
echo $dist[$dst] . "\n";

Complexity

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

Implementation notes

  • PHP: $dist doubles as the visited check, $parent records predecessors (null at the source), and a head 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.