Djikstra algorithm in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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