1 回答
TA贡献1809条经验 获得超8个赞
使用这样的结构会更好:
$data =[
"Y1DP480P" => ["FDVII005" => true],
"Y1DPMS7M" => ["Y1DP480P" => true, "Y1DP4860" => true, "Y1ENDCYP" => true],
// ...etc
];
因此,每个键都有一组子键,可以从第一个键开始一步到达。尽管集合不存在,但您通常会这样模仿:使用带有true值的关联数组(或者您喜欢的任何东西)。这也将忽略您在输入中可能存在的重复条目。
然后,标准的 BFS 将非常有效:
$input = "aaaaaaaa T bbbbbbbb ID=000
aaaaaaaa T cccccccc ID=000
cccccccc T eeeeeeee ID=000
bbbbbbbb T dddddddd ID=000
dddddddd T eeeeeeee ID=000
eeeeeeee T gggggggg ID=000";
// Convert input to the data structure:
$data = [];
foreach (explode("\n", $input) as $line) {
list($a, $b) = explode(" T ", substr($line, 0, 19));
$data[$a][$b] = true;
if (!isset($data[$b])) $data[$b] = [];
}
function shortestPath($data, $source, $target) { // Perform a BFS
$comeFrom[$source] = null;
$frontier = [$source];
while (count($frontier)) {
$nextFrontier = [];
foreach ($frontier as $key) {
if ($key == $target) {
$path = [];
while ($key) { // unwind the comeFrom info into a path
$path[] = $key;
$key = $comeFrom[$key];
}
return array_reverse($path); // the path needs to go from source to target
}
foreach ($data[$key] as $neighbor => $_) {
if (isset($comeFrom[$neighbor])) continue;
$comeFrom[$neighbor] = $key;
$nextFrontier[] = $neighbor;
}
}
$frontier = $nextFrontier;
}
}
$path = shortestPath($data, "aaaaaaaa", "gggggggg");
print_r($path); // ["aaaaaaaa", "cccccccc", "eeeeeeee", "gggggg"]
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报