From c7c8827628f01326fc24a59f56b9f8cb24dc50e8 Mon Sep 17 00:00:00 2001 From: miholeus Date: Mon, 19 Mar 2018 19:51:31 +0300 Subject: [PATCH] php dijkstras algorithm (#60) --- .../php/01_dijkstras_algorithm.php | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 07_dijkstras_algorithm/php/01_dijkstras_algorithm.php 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);