广度优先算法
<?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); ?>
生命只有一次。

浙公网安备 33010602011771号