Example #1
0
 public function computePath(Node $source, Node $target)
 {
     if (!$this->grid instanceof NodeGrid) {
         throw new \RuntimeException('Invalid Grid');
     }
     $priorityQueue = new NodePriorityQueueMin();
     $distanceMap = new NodeMap();
     $previousMap = new NodeMap();
     $priorityQueue->insert($source, 0);
     $distanceMap->insert($source, 0);
     while (!$priorityQueue->isEmpty()) {
         $node = $priorityQueue->extract();
         if ($node->getId() === $target->getId()) {
             return new NodePath($previousMap->lookupFrom($node));
         }
         $neighbors = $this->grid->getWalkableNeighbors($node);
         foreach ($neighbors as $neighbor) {
             $alternativeDistance = $distanceMap->lookup($node) + $this->distance->compute($node, $neighbor);
             if (!$distanceMap->exists($neighbor) || $alternativeDistance < $distanceMap->lookup($neighbor)) {
                 $priorityQueue->insert($neighbor, $alternativeDistance);
                 $distanceMap->insert($neighbor, $alternativeDistance);
                 $previousMap->insert($neighbor, $node);
             }
         }
     }
     return array();
     // no path found
 }
Example #2
0
 public function computePath(Node $source, Node $target)
 {
     if (!$this->grid instanceof NodeGrid) {
         throw new \RuntimeException('Invalid Grid');
     }
     $fScorePriorityQueue = new NodePriorityQueueMin();
     $gScoreMap = new NodeMap();
     $openedMap = new NodeMap();
     $closedMap = new NodeMap();
     $previousMap = new NodeMap();
     $fScorePriorityQueue->insert($source, 0);
     $gScoreMap->insert($source, 0);
     $openedMap->insert($source);
     while (!$fScorePriorityQueue->isEmpty()) {
         $node = $fScorePriorityQueue->extract();
         $closedMap->insert($node);
         if ($node->getId() === $target->getId()) {
             return new NodePath($previousMap->lookupFrom($node));
         }
         $neighbors = $this->grid->getWalkableNeighbors($node);
         foreach ($neighbors as $neighbor) {
             if ($closedMap->exists($neighbor)) {
                 continue;
             }
             $gScore = $gScoreMap->lookup($node) + $this->distance->compute($node, $neighbor);
             if (!$openedMap->exists($neighbor) || $gScore < $gScoreMap->lookup($neighbor)) {
                 $fScore = $gScore + $this->heuristic->compute($node, $target);
                 $fScorePriorityQueue->insert($neighbor, $fScore);
                 $gScoreMap->insert($neighbor, $gScore);
                 $openedMap->insert($neighbor);
                 $previousMap->insert($neighbor, $node);
             }
         }
     }
     // no path found
     return array();
 }