Convert function from recursion to iteration

后端 未结 4 727
耶瑟儿~
耶瑟儿~ 2021-01-01 06:19

I have this function that I wrote that is abysmally slow since php does not handle recursion well. I am trying to convert it to a while loop, but am having trouble wrapping

4条回答
  •  伪装坚强ぢ
    2021-01-01 06:56

    I'm not going to convert your code, but you can convert a recusive function into an iterative one by creating a stack:

    $stack= array();
    

    And instead of invoking $this->findroute(), push your parameters onto this stack:

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

    Now surround basically everything in your function into a while loop draining the stack after having primed it:

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

提交回复
热议问题