Advertisement
tsuedeun

Untitled

Jun 8th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.76 KB | None | 0 0
  1. <?php
  2. class Dijkstra {
  3.     private const INFINIRY = 1e9;
  4.     private
  5.         $graph,
  6.         $used = [],
  7.         $sumWays = [],
  8.         $path = [];
  9.  
  10.     public function __construct($graph) {
  11.         $this->graph = $graph;
  12.     }
  13.  
  14.     public function main($from, $to) {
  15.         $this->init();
  16.         $this->sumWays[$from] = 0;
  17.         while($currNode = $this->findNearestUnusedNode())
  18.             $this->setSumWaysToNextNodes($currNode);
  19.         return $this->restorePath($from, $to);
  20.     }
  21.  
  22.     private function init() {
  23.         foreach ($this->graph->getNodes() as $node) {
  24.             $this->used[$node] = false;
  25.             $this->sumWays[$node] = self::INFINIRY;
  26.         }
  27.     }
  28.  
  29.     private function findNearestUnusedNode() {
  30.         $nearestNode = '';
  31.         foreach ($this->graph->getNodes() as $node)
  32.             if (!$this->used[$node])
  33.                 if ($nearestNode == '' || $this->sumWays[$node] < $this->sumWays[$nearestNode])
  34.                     $nearestNode = $node;
  35.         return $nearestNode;
  36.     }
  37.  
  38.     private function setSumWaysToNextNodes($currentNode) {
  39.         $this->used[$currentNode] = true;
  40.         foreach ($this->graph->getEdges($currentNode) as $nextNode => $length)
  41.             if (!$this->used[$nextNode]) {
  42.                 $newSumWays = $this->sumWays[$currentNode] + $length;
  43.                 if ($newSumWays < $this->sumWays[$nextNode]) {
  44.                     $this->sumWays[$nextNode] = $newSumWays;
  45.                     $this->path[$nextNode] = $currentNode;
  46.                 }
  47.             }
  48.     }
  49.  
  50.     private function restorePath($from, $to) {
  51.         $path = $to;
  52.         while ($to != $from) {
  53.             $to = $this->path[$to];
  54.             $path = $to.$path;
  55.         }
  56.         return $path;
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement