在深度优先搜索中实现显式堆栈

ser*_*ten 7 php algorithm recursion graph depth-first-search

我有一个特别大的图形,因为它使用了过多的内存,因此使用递归几乎不可能遍历.

下面是我的深度优先函数,使用递归:

public function find_all_paths($start, $path)
{
    $path[] = $start;
    if (count($path)==25) /* Only want a path of maximum 25 vertices*/ {
        $this->stacks[] = $path;
        return $path;

    }
    $paths = array();

    for($i = 0; $i < count($this->graph[$start])-1; $i++) {
        if (!in_array($this->graph[$start][$i], $path)) {
     $paths[] = $this->find_all_paths($this->graph[$start][$i], $path);

        }
    }


    return $paths;
}
Run Code Online (Sandbox Code Playgroud)

我想重写这个函数,所以它是非递归的.我假设我需要创建某种类型的队列,并使用array_shift()函数的哪个部分弹出值,以及如何确保排队的顶点被保留(以便最终路径启用$this->stacks)?

Kha*_*d.K 1

它不需要指数空间,树中的路径数等于叶子的数量,每个叶子从根开始只有 1 条路径..

这是对任意二叉树的 DFS 简单搜索:

// DFS: Parent-Left-Right
public function dfs_search ( $head, $key )
{
    var $stack = array($head);
    var $solution = array();

    while (count($stack) > 0)
    {
        $node = array_pop($stack);

        if ($node.val == $key)
        {
            $solution[] = $node;
        }

        if ($node.left != null)
        {
            array_push($stack, $node.left);
        }

        if ($node.right != null)
        {
            array_push($stack, $node.right);
        }
    }

    return $solution;
}
Run Code Online (Sandbox Code Playgroud)

你需要找到树中的所有路径只是分支和分叉,这意味着每当你分支时,每个分支都会获取当前路径的副本..这是我写的1行递归分支和分叉:

// Branch & Fork
public function dfs_branchFork ( $node, $path )
{
    return array($path)
        +($node.right!=null?dfs_branchFork($node.right, $path+array($node)):null)
        +($node.left!=null?dfs_branchFork($node.left, $path+array($node)):null);
}
Run Code Online (Sandbox Code Playgroud)