广度优先算法

<?php
class BFSearch{

    public $pic = [];
    private $searchQueue = null;

    public function setPic( $pic ){
        $this->pic = $pic;
    }

    public function find( $from , $to ){

        if( $this->searchQueue === null ){
            $this->searchQueue = $this->pic[$from];
        }
        $hasFind = false;
        $hasChecked = [];
        while ( $next = array_shift($this->searchQueue) ){
            if( isset($hasChecked[$next]) ){
                continue;
            }
            $hasChecked[$next] = true;
            if( strpos( $next , $to )   ){
                $hasFind = true;
                echo $next."\n";
                break;
            }else{
                $paths = explode('_' ,$next);
                $next = $paths[count($paths)-1];
                foreach ( $this->pic[$next] as $t ){
                    $path = $from."_".$next."_".$t;
                    array_push($this->searchQueue, $path);
                }
            }
        }
        return $hasFind;

    }

}

$pic = [
    'shenyang' => ['liaoyang'],
    'liaoyang' => ['shenyang','anshan'],
    'dalian' =>['anshan'],
    'anshan' => ['dalian','liaoyang'],
    'dandong' => ['dalian']
];

$bfClass = new BFSearch();
$bfClass->setPic($pic);
$res = $bfClass->find('shenyang', 'liaoyang');
var_dump($res);

?>

 

posted @ 2020-08-10 10:29  ﹏Sakura  阅读(150)  评论(0)    收藏  举报