Iterative deepening of search depth in PHP arrays

Is it possible to implement the IDDFS algorithm in PHP with arrays at the levels?

Suppose the following tree:

A / \ BC / \ \ DEF 

Calling getNodes(A) results in an array (B, C) and similarly getNodes(B) in an array (D, E). I already wrote the getNodes function to use it with the BFS algorithm, which, unfortunately, is too slow.

Comment formatted code form:

 function bfs($start,$target){ $dist = 0; if(empty($queue)){ $queue = array(); }; if(empty($checked)){ $checked = array(); }; array_push($queue, $start); while(!empty($queue)): $dist = $dist + 1; $newqueue = array(); foreach($queue as $node){ if(!in_array($node,$checked)){ array_push($checked,$node); $nodes=getNodes($node); if(checkNode($nodes,$target)){ return $dist; }else{ $newqueue=$nodes; } } $queue = $newqueue; } endwhile; return false; } 
+4
source share
1 answer

In a recursive perspective, the function for this might look like this:

 <?php function getNode($needle, $target) { $res = null; foreach($target as $key=>$val) { if($key === $needle) { $res = $target[$key]; break; } elseif(is_array($target[$key])) $res = getNode($needle, $target[$key]); } return $res; } 

verified using:

 $arr = array( 'a' => array( 'b' => array( 'water' ), 'c' => array( 'earth' ) ) ); var_dump(getNode('a', $arr)); 
0
source

All Articles