HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Dijkstra's algorithm in PHP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
algorithmphpdijkstra

Problem

This is Dijkstra's algorithm in PHP. Regarding the data structure, I use a 2-dimensional array $_distArr[m][n]=length to store it. Are there any improvements for this?

$a and $b are the start and the end node, respectively.

$val) if(!empty($Q[$key]) && $Q[$min] + $val ";
echo "From $a to $b";
echo "The length is ".$S[$b][1];
echo "Path is ".implode('->', $path);

Solution

This implementation is great and works well, but you should add an "escape door" when no path is found.

For instance, remove these two lines:

$_distArr[4][5] = 6;
...
$_distArr[6][5] = 9;


If you comment both lines, you enter an infinite loop.

To avoid this problem, I think you can add these lines right before the "calculating while" loop:

if (!array_key_exists($b, $S)) {
    echo "Found no way.";
    return;
}


Then you're set; no infinite loop!

Code Snippets

$_distArr[4][5] = 6;
...
$_distArr[6][5] = 9;
if (!array_key_exists($b, $S)) {
    echo "Found no way.";
    return;
}

Context

StackExchange Code Review Q#75641, answer score: 5

Revisions (0)

No revisions yet.