微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 将函数从递归转换为迭代

我有这个函数,我写的是非常慢,因为PHP不能很好地处理递归.我试图将它转换为while循环,但我无法绕过如何做到这一点.

谁能给我一些提示

    public function findRoute($curLoc, $distanceSoFar, $expectedValue) {

    $this->locationsVisited[$curLoc] = true;
    $expectedValue += $this->locationsArray[$curLoc]*$distanceSoFar;

    $at_end = true;
    for($i = 1; $i < $this->numLocations; $i++) {
        if($this->locationsVisited[$i] == false) {
            $at_end = false;

            if($expectedValue < $this->bestEV)
                $this->findRoute($i, $distanceSoFar + $this->distanceArray[$curLoc][$i], $expectedValue);
        }
    }

    $this->locationsVisited[$curLoc] = false;

    if($at_end) {
        if($expectedValue < $this->bestEV) {
            $this->bestEV = $expectedValue;
        }
    }
}

解决方法:

我不打算转换你的代码,但你可以通过创建一个堆栈将一个recusive函数转换为迭代函数

$stack= array();

而不是调用$this-> findroute(),将您的参数推送到此堆栈:

$stack[] = array($i, $distanceSoFar + $this->distanceArray[$curLoc][$i], $expectedValue);

现在将函数中的所有内容基本上包围在一个while循环中,在启动它之后耗尽堆栈:

while ($stack) { 
    // Do stuff you already do in your function here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐