7

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

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

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;
}

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

4

1 回答 1

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;
}

在树中查找所有路径所需的只是 Branch & Fork,这意味着每当您分支时,每个分支都会获取当前路径的副本.. 这是我写的 1 行递归分支 & fork:

// 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);
}
于 2013-04-06T04:50:59.863 回答