1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Letournel\PathFinder\Algorithms\ShortestPath; |
4
|
|
|
|
5
|
|
|
use Letournel\PathFinder\AlgorithmShortestPath; |
6
|
|
|
use Letournel\PathFinder\Core\Node; |
7
|
|
|
use Letournel\PathFinder\Core\NodeGrid; |
8
|
|
|
use Letournel\PathFinder\Core\NodeMap; |
9
|
|
|
use Letournel\PathFinder\Core\NodePath; |
10
|
|
|
use Letournel\PathFinder\Core\NodePriorityQueueMin; |
11
|
|
|
use Letournel\PathFinder\Distance; |
12
|
|
|
|
13
|
|
|
class Dijkstra implements AlgorithmShortestPath |
14
|
|
|
{ |
15
|
|
|
/* |
16
|
|
|
* For more info see |
17
|
|
|
* http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm |
18
|
|
|
*/ |
19
|
|
|
|
20
|
|
|
private |
21
|
|
|
$distance, |
|
|
|
|
22
|
|
|
$grid; |
23
|
|
|
|
24
|
|
|
public function __construct(Distance $distance) |
25
|
|
|
{ |
26
|
|
|
$this->distance = $distance; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function setGrid(NodeGrid $grid) |
30
|
|
|
{ |
31
|
|
|
$this->grid = $grid; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function computeLength(Node $source, Node $target) |
35
|
|
|
{ |
36
|
|
|
$shortestPath = $this->computePath($source, $target); |
37
|
|
|
|
38
|
|
|
return $shortestPath->computeLength($this->distance); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function computePath(Node $source, Node $target) |
42
|
|
|
{ |
43
|
|
|
if(! $this->grid instanceof NodeGrid) |
44
|
|
|
{ |
45
|
|
|
throw new \RuntimeException('Invalid Grid'); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$priorityQueue = new NodePriorityQueueMin(); |
49
|
|
|
$distanceMap = new NodeMap(); |
50
|
|
|
$previousMap = new NodeMap(); |
51
|
|
|
|
52
|
|
|
$priorityQueue->insert($source, 0); |
53
|
|
|
$distanceMap->insert($source, 0); |
|
|
|
|
54
|
|
|
|
55
|
|
|
while(! $priorityQueue->isEmpty()) |
56
|
|
|
{ |
57
|
|
|
$node = $priorityQueue->extract(); |
58
|
|
|
|
59
|
|
|
if($node->getId() === $target->getId()) |
60
|
|
|
{ |
61
|
|
|
return new NodePath($previousMap->lookupFrom($node)); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$neighbors = $this->grid->getWalkableNeighbors($node); |
65
|
|
|
foreach($neighbors as $neighbor) |
66
|
|
|
{ |
67
|
|
|
$alternativeDistance = $distanceMap->lookup($node) + $this->distance->compute($node, $neighbor); |
68
|
|
|
if(! $distanceMap->exists($neighbor) || $alternativeDistance < $distanceMap->lookup($neighbor)) |
69
|
|
|
{ |
70
|
|
|
$priorityQueue->insert($neighbor, $alternativeDistance); |
71
|
|
|
$distanceMap->insert($neighbor, $alternativeDistance); |
72
|
|
|
$previousMap->insert($neighbor, $node); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return array(); // no path found |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
Only declaring a single property per statement allows you to later on add doc comments more easily.
It is also recommended by PSR2, so it is a common style that many people expect.