Skip to content

Instantly share code, notes, and snippets.

@tonysm
Created January 27, 2020 14:17
Show Gist options
  • Save tonysm/cf123d855823779bfc70951e5d9ee01d to your computer and use it in GitHub Desktop.
Save tonysm/cf123d855823779bfc70951e5d9ee01d to your computer and use it in GitHub Desktop.
Djikstra Algo in PHP
<?php
$graph = [
"start" => [
"a" => 6,
"b" => 2,
],
"a" => [
"end" => 1
],
"b" => [
"a" => 3,
"end" => 5
],
"end" => [],
];
$costs = [
"a" => 6,
"b" => 2,
"end" => INF,
];
$parents = [
"a" => "start",
"b" => "start",
"end" => null,
];
$processed = [];
function findLowestCostNode($costs, $processed) {
$lowestCost = INF;
$nodeWithLowestCost = null;
foreach ($costs as $n => $nCost) {
if ($nCost < $lowestCost && !in_array($n, $processed)) {
$lowestCost = $nCost;
$nodeWithLowestCost = $n;
}
}
return $nodeWithLowestCost;
}
$node = findLowestCostNode($costs, $processed);
while ($node !== null) {
$cost = $costs[$node];
$neighbors = $graph[$node];
foreach ($neighbors as $n => $nCost) {
$newCost = $cost + $nCost;
if ($costs[$n] > $newCost) {
$costs[$n] = $newCost;
$parents[$n] = $node;
}
}
$processed[] = $node;
$node = findLowestCostNode($costs, $processed);
}
function getFinalPath($parents) {
$path = [];
$node = "end";
while($node !== "start") {
array_unshift($path, $node);
$node = $parents[$node];
}
array_unshift($path, "start");
return implode(' -> ', $path);
}
echo "=== LOWEST COST UNTIL END ===".PHP_EOL;
print_r($costs["end"]);
echo PHP_EOL;
echo "=== SHORTEST PATH ===".PHP_EOL;
print_r(getFinalPath($parents));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment