コード例 #1
0
 /**
  * @param Digraph $graph
  * @param int $vertex
  */
 private function depthSearch(Digraph $graph, int $vertex)
 {
     $this->onStack[$vertex] = true;
     $this->marked[$vertex] = true;
     foreach ($graph->adjacent($vertex) as $item) {
         if ($this->hasCircle()) {
             return;
         } else {
             if (!isset($this->marked[$item])) {
                 $this->edgeTo[$item] = $vertex;
                 $this->depthSearch($graph, $item);
             } else {
                 if ($this->onStack[$item]) {
                     $this->circle = new Stack();
                     for ($x = $vertex; $x !== $item; $x = $this->edgeTo[$x]) {
                         $this->circle->add($x);
                     }
                     $this->circle->add($vertex);
                     $this->circle->add($item);
                 }
             }
         }
     }
     $this->onStack[$vertex] = false;
 }
コード例 #2
0
 /**
  * @param int $vertex
  * @return Iterator|null
  */
 public function pathTo(int $vertex)
 {
     if (!$this->hasPathTo($vertex)) {
         return null;
     }
     $path = new Stack();
     for ($x = $vertex; $x != $this->startVertex; $x = $this->edgeTo[$x]) {
         $path->add($x);
     }
     $path->add($this->startVertex);
     return $path;
 }
コード例 #3
0
ファイル: test_stack.php プロジェクト: YuraMalahov/algorithms
<?php

use Base\Stack;
spl_autoload_register(function ($class) {
    $file = str_replace('\\', '/', $class);
    require "../{$file}.php";
});
$stack = new Stack();
$stack->add(1);
$stack->add(2);
$stack->add(3);
foreach ($stack as $key => $value) {
    echo "{$key} => {$value}\n";
}
$stack->add(7);
$stack->add(8);
$stack->add(9);
foreach ($stack as $key => $value) {
    echo "{$key} => {$value}\n";
}