diff --git a/07_dijkstras_algorithm/php/01_dijkstras_algorithm.php b/07_dijkstras_algorithm/php/01_dijkstras_algorithm.php new file mode 100644 index 0000000..c7782eb --- /dev/null +++ b/07_dijkstras_algorithm/php/01_dijkstras_algorithm.php @@ -0,0 +1,73 @@ + $cost) { + # If it's the lowest cost so far and hasn't been processed yet... + if ($cost < $lowestCost && !array_key_exists($node, $processed)) { + # ... set it as the new lowest-cost node. + $lowestCost = $cost; + $lowestCostNode = $node; + } + } + + return $lowestCostNode; +} + +# Find the lowest-cost node that you haven't processed yet. +$node = findLowestCodeNode($costs); + +# If you've processed all the nodes, this while loop is done. +while ($node) { + $cost = $costs[$node]; + # Go through all the neighbors of this node. + $neighbors = $graph[$node]; + foreach (array_keys($neighbors) as $n) { + $newCost = $cost + $neighbors[$n]; + # If it's cheaper to get to this neighbor by going through this node... + if ($costs[$n] > $newCost) { + # ... update the cost for this node. + $costs[$n] = $newCost; + # This node becomes the new parent for this neighbor. + $parents[$n] = $node; + } + } + # Mark the node as processed. + $processed[$node] = true; + # Find the next node to process, and loop. + $node = findLowestCodeNode($costs); +} + +print("Cost from the start to each node:"); +var_dump($costs);