Advertisement
tsuedeun

Untitled

Jun 8th, 2019
470
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.16 KB | None | 0 0
  1. <?php
  2. class Walker {
  3.     public $graph, $path;
  4.  
  5.     public function __construct($graph) {
  6.         $this->graph = $graph;
  7.         $this->path = [];
  8.     }
  9.  
  10.     public function DepthRec($node) { //РЕКУРРЕНТНЫЙ ОБХОД ВГЛУБИНУ
  11.         $this->path[$node] = true;
  12.         foreach ($this->graph->getEdges($node) as $node2 => $length)
  13.             if (!$this->path[$node2])
  14.                 $this->DepthRec($node2);
  15.     }
  16.  
  17.     public function DepthIter($node) { //ИТЕРАТИВНЫЙ АЛГОРИТМ ОБХОДА ГРАФА ВГЛУБИНУ
  18.         $path = [];
  19.         $stack = new Stack();
  20.         $stack->put($node);
  21.         while ($stack->last != null) {
  22.             $curr = $stack->get();
  23.             $path[$curr] = true;
  24.             foreach ($this->graph->getEdges($curr) as $node2 => $length)
  25.                 if (!$path[$node2] && !$stack->contains($node2))
  26.                     $stack->put($node2);
  27.         }
  28.         return $path;
  29.     }
  30.  
  31.     function waves($node) { //ИТЕРАТИВНЫЙ АЛГОРИТМ ОБХОДА ГРАФА В ШИРИНУ
  32.         $path = [];
  33.         $wayToNode = [];
  34.         $queue = new Queue();
  35.         $queue->put($node);
  36.         $wayToNode[$node] = 0;
  37.         while ($queue->first != null) {
  38.             $curr = $queue->get();
  39.             $path[$curr] = true;
  40.             foreach ($this->graph->getEdges($curr) as $node2 => $length)
  41.                 if (!$path[$node2] && !$queue->contains($node2)) {
  42.                     $queue->put($node2);
  43.                     if (!$wayToNode[$node2])
  44.                         $wayToNode[$node2] = $wayToNode[$curr] + 1;
  45.                 }
  46.         }
  47.         return $wayToNode;
  48.     }
  49.  
  50.     function shortestWay($node1, $node2) {
  51.         $ways = $this->waves($node2);
  52.         $nodes = $node1;
  53.         $shortestWay[] = $node1;
  54.         for ($i = 0; $i < $ways[$node1]; $i++) {
  55.             foreach ($this->graph->getEdges($nodes) as $k => $v)
  56.                 if ($ways[$k] == $ways[$node1] - 1 - $i) {
  57.                     $shortestWay[] = $k;
  58.                     $nodes = $k;
  59.                     break;
  60.                 }
  61.         }
  62.         return $shortestWay;
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement