【发布时间】:2009-12-30 22:38:29
【问题描述】:
我写的这个函数非常慢,因为 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;
}
}
}
【问题讨论】:
-
您是否尝试过将某种调试/打印语句添加到 for 循环的主体中,显示递归发生的时间和次数。从检查来看,代码对我来说有点奇怪。在转换为使用迭代之前,我会检查一下。