方法一:(找到最短路径就跳出有限制不推荐)
<?PHP
$maps = [
// 点 // 相邻节点列表
1001 => [1002,1003,1005,1008,1009],
1002 => [1001,1008],
1003 => [1001,1005,1009],
1005 => [1001,1003,1004,1009],
1008 => [1001,1002,1009],
1009 => [1001,1003,1004,1005,1007,1008],
1004 => [1005,1009],
1007 => [1009]
];
$obj = new parse($maps);
$obj->find('1002', '1007');
echo $obj->getBest();
class parse{
var $data = array();
var $used = array();
var $chain = array();
function parse($data){
$this->data = $data;
}
/**
* $start 开始节点
* $end 结束节点
* $chain 当前查找路线的经过节点
*/
function find($start, $end, $chain=array()){
//将起始节点加入当前朋友链中
$chain[] = $start;
//判断当前起点是否有朋友
if(!isset($this->data[$start]))
return;
//判断当前的起点是否认识终点
if(in_array($end, $this->data[$start])){
$chain[] = $end;
$this->chain = $chain;
return ;
}
//如果当前"未完成路径" 比 "目前的最优路径" 长, 停止当前循环
if(sizeof($chain)>=sizeof($this->chain) && sizeof($this->chain)!=0)
return;
//继续递归循环
foreach($this->data[$start] as $value)
if(!in_array($value, $chain))
$this->find($value, $end, $chain);
}
function getBest(){
$str = implode('->', $this->chain);
return $str==null? "can't relation": $str;
}
}
?>
方法二:(找到所有路径,自己选择推荐)
<?PHP
$maps = [
// 点 // 相邻节点列表
1001 => [1002,1003,1005,1008,1009],
1002 => [1001,1008],
1003 => [1001,1005,1009],
1005 => [1001,1003,1004,1009],
1008 => [1001,1002,1009],
1009 => [1001,1003,1004,1005,1007,1008],
1004 => [1005,1009],
1007 => [1009]
];
$obj = new parse($maps);
$obj->find(1002, 1007);
class parse{
var $data = array();
function parse($data){
$this->data = $data;
}
/**
* $start 开始节点
* $end 结束节点
* $chain 当前查找路线的经过节点
*/
function find($start, $end, $chain=array()){
//将起始节点加入当前节点链中
$chain[] = $start;
//判断当前起点是否有相邻节点
if(!isset($this->data[$start]))
return;
//判断当前的起点是否是终点的相邻节点
if(in_array($end, $this->data[$start])){
echo implode('->', $chain)."->$end".'<br/>';
return ;
}
//继续递归循环
foreach($this->data[$start] as $value)
if(!in_array($value, $chain))
$this->find($value, $end, $chain);
}
}
?>