美文网首页
PHP实现的BFS、DFS

PHP实现的BFS、DFS

作者: 文沐2023 | 来源:发表于2021-03-02 16:49 被阅读0次

<?php
$tree = [

    "A" => ["B", "C","D"],

    "B" => ["A","E", "F"],

    "C" => ["G","E","A"],

    "D" => ["A"],

    "F" => ["B","E"],

    "E" => ["B","C", "F","H"],

    "G" =>["C"],

    "H" =>["E"],

];

bfs($tree, "A");

echo PHP_EOL;

dfs($tree, "A");

function bfs($tree, $node) {

    $queue = [$node];

    $usedQueue = [

        $node =>true

    ];

    while (!empty($queue)) {

        echo $node = array_shift($queue);

        if (!isset($tree[$node])) continue;

        foreach ($tree[$node] as $childNode) {

            if ($usedQueue[$childNode]) {

                continue;

            }

            array_push($queue, $childNode);

            $usedQueue[$childNode] = true;

        }

    }

}

function dfs($tree, $node) {

    $queue = [$node];

    $usedQueue = [

        $node =>true

    ];

    while (!empty($queue)) {

        echo $node = array_pop($queue);

        if (!isset($tree[$node])) continue;

        foreach ($tree[$node] as $childNode) {

            if ($usedQueue[$childNode]) {

                continue;

            }

            array_push($queue, $childNode);

            $usedQueue[$childNode] = true;

        }

    }

}

?>

相关文章

网友评论

      本文标题:PHP实现的BFS、DFS

      本文链接:https://www.haomeiwen.com/subject/yxrxqltx.html