Skip to content

Commit c7c8827

Browse files
miholeusegonSchiele
authored andcommitted
php dijkstras algorithm (egonSchiele#60)
1 parent bff0bba commit c7c8827

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
<?php
2+
$graph = [];
3+
$graph["start"] = [];
4+
$graph["start"]["a"] = 6;
5+
$graph["start"]["b"] = 2;
6+
7+
$graph["a"] = [];
8+
$graph["a"]["fin"] = 1;
9+
10+
$graph["b"] = [];
11+
$graph["b"]["a"] = 3;
12+
$graph["b"]["fin"] = 5;
13+
14+
$graph["fin"] = [];
15+
16+
# the costs table
17+
$infinity = PHP_INT_MAX;
18+
$costs = [];
19+
$costs["a"] = 6;
20+
$costs["b"] = 2;
21+
$costs["fin"] = $infinity;
22+
23+
# the parents table
24+
$parents = [];
25+
$parents["a"] = "start";
26+
$parents["b"] = "start";
27+
$parents["fin"] = null;
28+
29+
$processed = [];
30+
31+
function findLowestCodeNode(array $costs) {
32+
$lowestCost = PHP_INT_MAX;
33+
$lowestCostNode = null;
34+
global $processed;
35+
# Go through each node.
36+
foreach ($costs as $node => $cost) {
37+
# If it's the lowest cost so far and hasn't been processed yet...
38+
if ($cost < $lowestCost && !array_key_exists($node, $processed)) {
39+
# ... set it as the new lowest-cost node.
40+
$lowestCost = $cost;
41+
$lowestCostNode = $node;
42+
}
43+
}
44+
45+
return $lowestCostNode;
46+
}
47+
48+
# Find the lowest-cost node that you haven't processed yet.
49+
$node = findLowestCodeNode($costs);
50+
51+
# If you've processed all the nodes, this while loop is done.
52+
while ($node) {
53+
$cost = $costs[$node];
54+
# Go through all the neighbors of this node.
55+
$neighbors = $graph[$node];
56+
foreach (array_keys($neighbors) as $n) {
57+
$newCost = $cost + $neighbors[$n];
58+
# If it's cheaper to get to this neighbor by going through this node...
59+
if ($costs[$n] > $newCost) {
60+
# ... update the cost for this node.
61+
$costs[$n] = $newCost;
62+
# This node becomes the new parent for this neighbor.
63+
$parents[$n] = $node;
64+
}
65+
}
66+
# Mark the node as processed.
67+
$processed[$node] = true;
68+
# Find the next node to process, and loop.
69+
$node = findLowestCodeNode($costs);
70+
}
71+
72+
print("Cost from the start to each node:");
73+
var_dump($costs);

0 commit comments

Comments
 (0)