foreach ($this->graph[$t] as $vertex) { if (!$this->visited[$vertex]) { // if not yet visited, enqueue vertex and mark as visited $q->enqueue($vertex); $this->visited[$vertex] = true; // add vertex to current node path $path[$vertex] = clone $path[$t]; $path[$vertex]->push($vertex); } } } } if (isset($path[$destination])) { echo "{$origin} to {$destination} in ", count($path[$destination]) - 1, " hops\n"; $sep = ''; foreach ($path[$destination] as $vertex) { echo $sep, $vertex; $sep = '->'; } echo "\n"; } else { echo "No route from {$origin} to {$destination}\n"; } } } $graph = array('A' => array('B', 'F'), 'B' => array('A', 'D', 'E'), 'C' => array('F'), 'D' => array('B', 'E'), 'E' => array('B', 'D', 'F'), 'F' => array('A', 'E', 'C')); $g = new Graph($graph); $g->leastHops('D', 'C'); $g->leastHops('B', 'F'); $g->leastHops('A', 'C'); $g->leastHops('A', 'G');