1 | <?php |
||
4 | class Dijkstra |
||
5 | { |
||
6 | protected $points; |
||
7 | protected $relations; |
||
8 | |||
9 | public function __construct($relations = NULL) |
||
15 | |||
16 | public function setRelations($relations) |
||
29 | |||
30 | public function generate() |
||
50 | |||
51 | private function dist($source, $point, &$visited = []) |
||
52 | { |
||
53 | $visited[$point] = TRUE; # Set current point as visited |
||
54 | |||
55 | # Prepare help variables |
||
56 | $min_ptr = -1; |
||
57 | $min = 0; |
||
58 | |||
59 | # Analyzes point neighborhood |
||
60 | foreach ($this->relations[$point] as $relation) { |
||
61 | if ($relation[0] != $source) { # If current point is different than source |
||
62 | if (empty($visited[$relation[0]])) { # If current point is not visited |
||
63 | if ($min_ptr == -1) { # When minimal point is not finded |
||
64 | $min_ptr = $relation[0]; |
||
65 | $min = $relation[1]; |
||
66 | } else { |
||
67 | if ($min > $relation[1]) { |
||
68 | $min_ptr = $relation[0]; |
||
69 | $min = $relation[1]; |
||
70 | } |
||
71 | } |
||
72 | } |
||
73 | |||
74 | # Change the shortest way to current point |
||
75 | if (isset($this->points[$point][0])) { |
||
76 | $first_field = $this->points[$point][0]; |
||
77 | } else { |
||
78 | $first_field = 0; |
||
79 | } |
||
80 | |||
81 | if (empty($this->points[$relation[0]])) { |
||
82 | $this->points[$relation[0]] = [ |
||
83 | $first_field + $relation[1], |
||
84 | ((empty($this->points[$point][1])) ? $point : $this->points[$point][1]) . ':' . $relation[0], |
||
85 | ]; |
||
86 | } else { |
||
87 | if ($this->points[$relation[0]][0] > ($this->points[$point][0] + $relation[1])) { |
||
88 | $this->points[$relation[0]] = [ |
||
89 | ((isset($this->points[$point][0])) ? $this->points[$point][0] : 0) + $relation[1], |
||
90 | ((empty($this->points[$point][1])) ? NULL : $this->points[$point][1] . ':') . $relation[0], |
||
91 | ]; |
||
92 | } |
||
93 | } |
||
94 | } |
||
95 | } |
||
96 | |||
97 | # If isset unvisited point with minimal way go for it |
||
98 | if ($min_ptr != -1) { |
||
99 | $this->dist($source, $min_ptr, $visited); |
||
100 | } |
||
101 | } |
||
102 | |||
103 | public function distances($point) |
||
108 | |||
109 | private static function validate($relations_array) |
||
136 | } |
||
137 |