Example #1
0
 /**
  * @param Graph $g
  * @param mixed $vertex
  * @param callable $callback A function to be called on each vertex
  *      If the function returns false, the graph is not traversed further
  * @return \GraPHPy\Vertex[]
  */
 public static function dfs(Graph $g, $vertex, $callback = null)
 {
     $stack = [[$g->getVertex($vertex)]];
     $callbackIsCallable = is_callable($callback);
     $discovered = [];
     $recursionStack = [];
     while (!empty($stack)) {
         $vertices = array_pop($stack);
         if (empty($vertices)) {
             array_pop($recursionStack);
         } else {
             $currentVertex = array_pop($vertices);
             array_push($stack, $vertices);
             if (in_array($currentVertex, $discovered)) {
                 continue;
             }
             $discovered[] = $currentVertex;
             if ($callbackIsCallable) {
                 if (!$callback($currentVertex, $discovered, $recursionStack)) {
                     break;
                 }
             }
             array_push($recursionStack, $currentVertex);
             array_push($stack, $currentVertex->getAdjacentVertices());
         }
     }
     return $discovered;
 }