开发者

Iterative deepening depth-first search in arrays PHP

开发者 https://www.devze.com 2023-03-29 07:19 出处:网络
Would it be possible to implement IDDFS algorithm in PHP with arrays in levels? Supposing the following tree:

Would it be possible to implement IDDFS algorithm in PHP with arrays in levels?

Supposing the following tree:

    A
   / \
  B   C
 / \   \  
D   E   F

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

Code formatted form comment:

function bfs($start,$target){
    $dist = 0; 

    if(empty($queue)){
        $queue = array(); 
    }; 

    if(empty($chec开发者_JAVA技巧ked)){
        $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;
}


In a recursive point of view, a function to do this could 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;
}

tested with:

$arr = array(
    'a' => array(
        'b' => array(
            'water'
        ),
        'c' => array(
            'earth'
        )
    )
);

var_dump(getNode('a', $arr));
0

精彩评论

暂无评论...
验证码 换一张
取 消