|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Letournel\PathFinder\Algorithms\TravelingSalesman; |
|
4
|
|
|
|
|
5
|
|
|
use Letournel\PathFinder\AlgorithmTravelingSalesman; |
|
6
|
|
|
use Letournel\PathFinder\Core\NodeGraph; |
|
7
|
|
|
use Letournel\PathFinder\Core\NodeMap; |
|
8
|
|
|
use Letournel\PathFinder\Core\NodePath; |
|
9
|
|
|
|
|
10
|
|
|
class NearestNeighbour implements AlgorithmTravelingSalesman |
|
11
|
|
|
{ |
|
12
|
|
|
/* |
|
13
|
|
|
* For more info see |
|
14
|
|
|
* http://en.wikipedia.org/wiki/Nearest_neighbour_algorithm |
|
15
|
|
|
*/ |
|
16
|
|
|
|
|
17
|
|
|
private |
|
18
|
|
|
$graph; |
|
|
|
|
|
|
19
|
|
|
|
|
20
|
|
|
public function setGraph(NodeGraph $graph) |
|
21
|
|
|
{ |
|
22
|
|
|
$this->graph = $graph; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public function computeRoute() |
|
26
|
|
|
{ |
|
27
|
|
|
if(! $this->graph instanceof NodeGraph) |
|
28
|
|
|
{ |
|
29
|
|
|
throw new \RuntimeException('Invalid Graph'); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
$vertexes = $this->graph->getVertexes(); |
|
33
|
|
|
if(count($vertexes) <= 2) |
|
34
|
|
|
{ |
|
35
|
|
|
return new NodePath($vertexes); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
$vertexFrom = array_shift($vertexes); |
|
39
|
|
|
$vertexTo = null; |
|
40
|
|
|
|
|
41
|
|
|
$pathMap = new NodeMap(); |
|
42
|
|
|
$pathMap->insert($vertexFrom, $vertexTo); |
|
|
|
|
|
|
43
|
|
|
while(! empty($vertexes)) |
|
44
|
|
|
{ |
|
45
|
|
|
$minimalVertexTo = null; |
|
46
|
|
|
$minimalEdge = INF; |
|
47
|
|
|
$edges = $this->graph->getEdgesFrom($vertexFrom); |
|
48
|
|
|
foreach($edges as $vertexToId => $edge) |
|
49
|
|
|
{ |
|
50
|
|
|
$vertexTo = $this->graph->getVertex($vertexToId); |
|
51
|
|
|
if(! $pathMap->exists($vertexTo) && $edge < $minimalEdge) |
|
52
|
|
|
{ |
|
53
|
|
|
$minimalVertexTo = $vertexTo; |
|
54
|
|
|
$minimalEdge = $edge; |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
$pathMap->insert($minimalVertexTo, $vertexFrom); |
|
59
|
|
|
unset($vertexes[$minimalVertexTo->getId()]); |
|
60
|
|
|
$vertexFrom = $minimalVertexTo; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
return new NodePath($pathMap->lookupFrom($vertexFrom)); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|
The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using
the property is implicitly global.
To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.