Thursday, December 2, 2010

Dijkstra's_algorithm in PHP


<html><body><pre>
<?php
$d['a']['b'] = 10;
$d['a']['c'] = 2;
$d['b']['d'] = 1;
$d['c']['d'] = 1;
$d['c']['e'] = 7;
$d['d']['e'] = 20;
$d['e']['f'] = 9;

$startNode = 'a';

$nodeStack = array();
array_push($nodeStack,$startNode);
while(count($nodeStack) > 0) {
$curr = array_pop($nodeStack);
foreach($d[$curr] as $v3 => $d3) {
array_push($nodeStack,$v3);
if($d[$startNode][$v3]) {
$newDist = $d[$startNode][$curr] + $d[$curr][$v3];
if($d[$startNode][$v3] > $newDist)
$d[$startNode][$v3] = $newDist;
} else {
$d[$startNode][$v3] = $d[$startNode][$curr] + $d[$curr][$v3];
}
}
}

print_r($d[$startNode]);
?>
</pre></body></html>

No comments:

Blog Archive