Skip to content

Instantly share code, notes, and snippets.

@u-mulder
Created August 16, 2019 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save u-mulder/39ebe70c24289d39ee0c8d686d315e36 to your computer and use it in GitHub Desktop.
Save u-mulder/39ebe70c24289d39ee0c8d686d315e36 to your computer and use it in GitHub Desktop.
Djikstra algorithm in php
<?php
/**
* Djikstra algorithm in php
*
* Input data from STDIN as:
*
* 4 8
* 1 2 6
* 1 3 2
* 1 4 10
* 2 4 4
* 3 1 5
* 3 2 3
* 3 4 8
* 4 2 1
* 1 4
* Answer: 9
*
* 5 4
* 1 2 1
* 2 3 1
* 3 4 1
* 4 5 1
* 1 5
* Answer: 4
*
* In case of no path - output -1
*/
function djikstra()
{
// Number of vertexes and edges
list($vertexCount, $edgesCount) = explode(' ', trim(fgets(STDIN)));
$totalDistancesToV = array_fill_keys(range(1, $vertexCount), INF);
$notCheckedV = array_fill_keys(range(1, $vertexCount), 1);
// Distance between vertexes
$distances = [];
while ($edgesCount--) {
list($from, $to, $distance) = explode(' ', trim(fgets(STDIN)));
if (empty($distances[$from])) {
$distances[$from] = [];
}
$distances[$from][$to] = (int)$distance;
}
// Start end vertexes to find distance between
list($searchFrom, $searchTo) = explode(' ', trim(fgets(STDIN)));
$searchFrom = (int)$searchFrom;
$totalDistancesToV[$searchFrom] = 0;
while (true) {
if (!empty($distances[$searchFrom])) {
foreach ($distances[$searchFrom] as $vertex => $distance) {
$totalDistancesToV[$vertex] = min(
$totalDistancesToV[$vertex],
$totalDistancesToV[$searchFrom] + $distance
);
}
}
unset($notCheckedV[$searchFrom]);
if ($notCheckedV) {
$minDistance = false;
foreach ($notCheckedV as $vertex => $v) {
if (false === $minDistance || $totalDistancesToV[$vertex] < $minDistance) {
$searchFrom = $vertex;
$minDistance = $totalDistancesToV[$vertex];
}
}
} else {
break;
}
}
echo ($totalDistancesToV[$searchTo] === INF ? -1 : $totalDistancesToV[$searchTo]) . PHP_EOL;
}
djikstra();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment