php算法 广度优先搜索

function findpersion($name, $list) {
	$checklist = [];
	$persionlist = array_keys($list);
	$result = false;
	$index = 0;
	while ($persionlist) {
		$index++;
		$persion = array_shift($persionlist);
		if (in_array($persion, $checklist)) {
			continue;
		}
		if ($persion == $name) {
			$result = true;
			break;
		} else {
			$checklist[] = $persion;
			if (isset($list[$persion]) && !empty($list[$persion]) && is_array($list[$persion])) {
				$persionlist += $list[$persion];
				$persionlist = array_merge($persionlist, $list[$persion]);
			}
		}
	}
	var_dump($index);
	return $result;
}
$list = [
	'lsswear' => ['abby'],
	'abby' => ['leo', 'lsswear'],
	'swear' => ['angle', 'yilai'],
];

$result = findpersion("leo", $list);
var_dump($result);

输出内容如下

int(5)
bool(true)

原文地址:php算法 广度优先搜索

获取更多内容,欢迎订阅公众号 “lsswear”。

你可能感兴趣的:(php,算法,php)