Dijkstra’s algorithm php code example
Example: Dijkstra’s algorithm php
$INT_MAX = 0x7FFFFFFF;
function MinimumDistance($distance, $shortestPathTreeSet, $verticesCount)
{
global $INT_MAX;
$min = $INT_MAX;
$minIndex = 0;
for ($v = 0; $v < $verticesCount; ++$v)
{
if ($shortestPathTreeSet[$v] == false && $distance[$v] <= $min)
{
$min = $distance[$v];
$minIndex = $v;
}
}
return $minIndex;
}
function PrintResult($distance, $verticesCount)
{
echo "" . "Vertex Distance from source" . "
";
for ($i = 0; $i < $verticesCount; ++$i)
echo "" . $i . "\t " . $distance[$i] . "
";
}
function Dijkstra($graph, $source, $verticesCount)
{
global $INT_MAX;
$distance = array();
$shortestPathTreeSet = array();
for ($i = 0; $i < $verticesCount; ++$i)
{
$distance[$i] = $INT_MAX;
$shortestPathTreeSet[$i] = false;
}
$distance[$source] = 0;
for ($count = 0; $count < $verticesCount - 1; ++$count)
{
$u = MinimumDistance($distance, $shortestPathTreeSet, $verticesCount);
$shortestPathTreeSet[$u] = true;
for ($v = 0; $v < $verticesCount; ++$v)
if (!$shortestPathTreeSet[$v] && $graph[$u][$v] && $distance[$u] != $INT_MAX && $distance[$u] + $graph[$u][$v] < $distance[$v])
$distance[$v] = $distance[$u] + $graph[$u][$v];
}
PrintResult($distance, $verticesCount);
}