I have a particularly large graph, making it nearly impossible to traverse using recursion because of the excessive amount of memory it uses.
Below is my depth-first function, using recursion:
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;
}
I would like to rewrite this function so it is non-recursive. I assume I will need to make a queue of some sort, and pop off values using array_shift()
but in which part of the function, and how do I make sure the queued vertices are preserved (to put the final pathway on $this->stacks
)?